我正在编写一个简单的游戏,并且在 CardLayout 中放置了 4 个 JPanel 的主框架。主框架如下所示:
private static JPanel[] panele = new JPanel[4];
private static JPanel panel;
public GameWindow()
{
super("Sokoban");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
panele[0] = new MainMenu();
panele[1] = new LoadGameMenu();
panele[2] = new SaveGameMenu();
panele[3] = new GameScene();
panel = new JPanel(new CardLayout());
//((MainMenu)panele[0]).setSaveOptionState(false);
panel.add(panele[0], "MainMenu");
panel.add(panele[1], "LoadGameMenu");
panel.add(panele[2], "SaveGameMenu");
panel.add(panele[3], "GameScene");
add(panel, BorderLayout.CENTER);
}
GameScene 面板对键盘输入有反应。首先我尝试了keylistener:
public GameScene() {
setFocusable(true);
initWorld(); //Drawing on JPanel takes place here
addKeyListener(new Keyboard());
}
class Keyboard extends KeyAdapter
{
private int key;
public void keyPressed(KeyEvent event)
{
System.out.println("Tu jestem");
key = event.getKeyCode();
if(key == KeyEvent.VK_ESCAPE)
{
Game.gra = new GameWindow(MenuAction.MAIN_MENU);
System.out.println("Escape");
}
那不起作用......所以我尝试了键绑定(简单实现):
public GameScene() {
setFocusable(true);
initWorld(); //Drawing on JPanel takes place here
// requestFocus();
setInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, getInputMap());
KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
getInputMap().put(key, "pressed");
getActionMap().put("pressed", new AbstractAction(){
public void actionPerformed(ActionEvent arg0) {
System.out.println("Spacja");
//Game.gra = new GameWindow(MenuAction.MAIN_MENU);
}
});
}
它仍然无法正常工作......我尝试添加 requestFocus 和 requestFocusInWindow() 但没有效果。任何想法如何解决它或做到这一点?
已找到解决方案。在键绑定中,我应该写:
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(key, "pressed");
安装:
getInputMap().put(key, "pressed");