2

我正在编写一个简单的游戏,并且在 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"); 
4

3 回答 3

3

试试这个:

setInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW, getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW));

编辑:作为参考,“每个 JComponent 都有一个动作映射和三个输入映射。”

于 2012-05-20T19:36:44.617 回答
2

通过使用Action,如图所示您可以将一个键(或组合)绑定到它,如此Action所示。如需更多指导,请编辑您的问题以包含使用其中一个或两个示例的sscce 。

于 2012-05-20T19:34:30.867 回答
1

我不知道这是否是你真正想要的,但如果你想在“GameScene”卡中时简单地对关键事件做出反应,你应该首先切换到这张卡(以抓住焦点):

        CardLayout cl = new CardLayout();
        panel = new JPanel(cl);
        ...
        add(panel, BorderLayout.CENTER);
        cl.show(panel, "GameScene");

还要查看您的代码 - 考虑使用JMenu和/或JTabbedPane.

于 2012-05-20T18:52:56.863 回答