Mat*_*tin 0 java swing awt keylistener
我有一些用Java绘画的经验.基本上我知道如何将关键监听器添加到框架中,但我想知道是否有任何其他方法如何添加所有这些方法,而不仅仅是在main方法之后或之前编写它们.这种方法使我的代码难以读取.
public class test extends JPanel {
public static JFrame frame;
public static JPanel panel;
public static int x;
public static int y;
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillOval(x,y,20,20);
}
public static void main(String args[]) {
test x=new test();
x.setBackground(Color.white);
frame=new JFrame();
frame.setSize(500,500);
frame.add(x);
frame.setVisible(true);
}
}
Run Code Online (Sandbox Code Playgroud)
是的,适配器减少了很多代码:
frame.addKeyListener(new KeyAdapter(){
@Override
public void keyTyped(KeyEvent e){
// do what ever you want
}
});
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,您还可以覆盖 keyPressed和keyReleased方法,但这仅对帧有效.如果您有时间,请查看KeyBindings.