【发布时间】:2011-08-12 22:07:50
【问题描述】:
我有一个托管我的 Applet 的 JFrame。小程序上有一个 KeyListener 来处理方向键和 enter/escape 键。
当我在 Eclipse 中运行我的 JFrame 时,一切正常,箭头键以及 enter 和 escape 键都有响应。
但是,当我将项目导出到 Executable Jar 文件时...箭头键仍然有效,但回车键和转义键无效。我该如何解决这个问题?
主类中的代码:
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 小程序的代码:
@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;
}
}
}
希望有人能帮我解决这个问题... Thnx
【问题讨论】:
-
为什么
FinalSnake是小程序而不是JPanel?如果它是一个面板,它可以添加到小程序或应用程序中,焦点问题很可能会消失。
标签: java applet keylistener