为什么我的keyListener在这段代码中不起作用?有人可以向我解释一下吗?我一直在尝试将它添加到我的框架中,但是当我运行文件时它仍然不起作用...一直在尝试做很多事情,但仍然无法弄明白^。^
package week3.position;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
/**
*
* @author Jelle Siderius
*/
public class Main {
public static void main(String[] args) {
createFrame();
}
public static void createFrame() {
final JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.setTitle("Vierkanten");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension dlp1 = new Dimension(300, 500);
final JPanel lp1 = new JPanel(new BorderLayout());
lp1.setPreferredSize(dlp1);
JPanel lp11 = new JPanel();
lp11.setPreferredSize(new Dimension(50, 500));
JPanel lp12 = new JPanel();
lp12.setPreferredSize(new Dimension(50, 500));
JPanel lp2 = new JPanel(new BorderLayout());
lp2.setBackground(Color.BLUE);
lp2.setSize(200, 500);
JPanel lp21 = new JPanel();
Dimension d21 = new Dimension(200, 100);
lp21.setPreferredSize(d21);
lp2.add(lp21, BorderLayout.NORTH);
JPanel lp22 = new JPanel();
Dimension d22 = new Dimension(200, 300);
lp22.setPreferredSize(d22);
JLabel lable22 = new JLabel("Aantal vierkanten: ");
final JTextField text22 = new JTextField(10);
JButton button22 = new JButton("Teken!");
ActionListener buttonClick = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int aantal = Integer.parseInt(text22.getText());
Circle circle = new Circle(aantal);
lp1.add(circle);
frame.revalidate();
frame.repaint();
if (circle.getekend == true) {
lp1.removeAll();
lp1.updateUI();
lp1.add(circle);
frame.revalidate();
frame.repaint();
}
}
};
lp22.add(lable22);
lp22.add(text22);
lp22.add(button22);
button22.addActionListener(buttonClick);
lp2.add(lp22, BorderLayout.CENTER);
JPanel lp23 = new JPanel();
Dimension d23 = new Dimension(200, 100);
lp23.setPreferredSize(d21);
lp2.add(lp23, BorderLayout.SOUTH);
frame.add(lp1, BorderLayout.CENTER);
frame.add(lp2, BorderLayout.EAST);
frame.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void keyPressed(KeyEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void keyReleased(KeyEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
});
frame.setVisible(true);
}
}