我真的不知道我做错了什么。只有重要事件有时注册
有时,关键事件登记,有时他们没有。
而我的意思是,有时当我运行Frogger2时,我得到注册事件,有时甚至没有。
看起来完全是随机的,关键事件注册与否。通常情况下,如果我暂时不测试任何东西并运行Frogger2事件注册,那么当我关闭它并重新运行完全相同的程序时,我就不会收到任何事件。
请帮忙。
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class Frogger2 extends JPanel {
public static JFrame frame;
public static Frogger2 F;
public Frogger2() {}
public Dimension getPreferredSize() { return new Dimension(500,500); }
public void paintComponent(Graphics g) { super.paintComponent(g); }
private int fdir;
public void moveLeft() {
travel(2);
}
public void moveRight() {
travel(0);
}
public void moveUp() {
travel(3);
}
public void moveDown() {
travel(1);
}
private void travel(int ddd) {
System.out.println(ddd);
}
private boolean step() {
System.out.println("FDIR: "+fdir);
return true;
}
public void start() {
fdir = 2;
while(true) {
boolean a = step();
if (!a) break;
try {
Thread.sleep(25);
} catch(Exception e) {}
}
}
public static void main(String[] args) {
frame = new JFrame("Frogger");
F = new Frogger2();
F.setDoubleBuffered(true);
frame.add(F);
frame.pack();
frame.setVisible(true);
frame.setResizable(false);
JPanel abc = (JPanel)frame.getContentPane();
abc.getInputMap().put(KeyStroke.getKeyStroke("LEFT"), "left");
abc.getActionMap().put("left", new AbstractAction() {
public void actionPerformed(ActionEvent e) {F.moveLeft();}
});
abc.getInputMap().put(KeyStroke.getKeyStroke("RIGHT"), "right");
abc.getActionMap().put("right", new AbstractAction() {
public void actionPerformed(ActionEvent e) {F.moveRight();}
});
abc.getInputMap().put(KeyStroke.getKeyStroke("UP"), "up");
abc.getActionMap().put("up", new AbstractAction() {
public void actionPerformed(ActionEvent e) {F.moveUp();}
});
abc.getInputMap().put(KeyStroke.getKeyStroke("DOWN"), "down");
abc.getActionMap().put("down", new AbstractAction() {
public void actionPerformed(ActionEvent e) {F.moveDown();}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
F.start();
}
}
- [*如何写一个按键侦听器*](HTTP “要发射的键盘事件,_must_有键盘焦点的组件。”://文档。 oracle.com/javase/tutorial/uiswing/events/keylistener.html) – trashgod