我有一个 JFrame 来托管我的 Applet。小程序上有一个 KeyListener 来处理箭头键和 Enter/Escape 键。
当我在 Eclipse 中运行 JFrame 时,一切正常,箭头键以及 Enter 和 Escape 键都有响应。
但是,当我将项目导出到可执行 Jar 文件时...箭头键仍然有效,但 Enter 和转义键不起作用。我该如何解决这个问题?
主类中的代码:
public static void main(String[] args) throws Exception {
new SnakeApp().snake();
}
public void snake() throws Exception {
// Set windows look
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
// Create window
JFrame window = new JFrame("FinalSnake");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add FinalSnake applet
FinalSnake finalSnake = new FinalSnake();
finalSnake.init();
finalSnake.start();
window.add(finalSnake);
// Set size
window.setResizable(false);
window.getContentPane().setPreferredSize(new Dimension(FinalSnake.GRIDSIZE * FinalSnake.GRIDX, FinalSnake.GRIDSIZE * FinalSnake.GRIDY));
window.pack();
// Set Icon
window.setIconImage(new ImageIcon(this.getClass().getResource("gfx/icon.png")).getImage());
// Center the frame
Dimension frameSize = Toolkit.getDefaultToolkit().getScreenSize();
window.setLocation((frameSize.width - window.getSize().width) / 2, (frameSize.height - window.getSize().height) / 2);
// Show the window
window.setVisible(true);
// And focus the FinalSnake applet
finalSnake.requestFocusInWindow();
}
来自 FinalSnake Applet 的代码:
@Override
public void keyPressed(KeyEvent e) {
if (this.world == null) {
if (e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_LEFT) {
this.gameType--;
if (this.gameType == 0) {
this.gameType = 2;
}
}
if (e.getKeyCode() == KeyEvent.VK_DOWN || e.getKeyCode() == KeyEvent.VK_RIGHT) {
this.gameType++;
if (this.gameType == 3) {
this.gameType = 1;
}
}
if (e.getKeyCode() == KeyEvent.VK_ENTER || e.getKeyCode() == KeyEvent.VK_SPACE) {
this.world = new World(this.gameType);
}
} else {
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
this.world = null;
}
}
}
希望有人能为我解决这个问题......谢谢
最佳答案
您可以尝试使用consume()
您的 KeyEvent
变量上的方法。它说:
Consumes this event so that it will not be processed in the default manner by the source which originated it.
我猜这将覆盖默认方式。
public void keyPressed(KeyEvent e) {
//Do your actions
e.consume();
}
关于java keylistener 导出后不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5788718/