Note that there are some explanatory texts on larger screens.

plurals
  1. POAdding keylistener to panel in CardLayout
    primarykey
    data
    text
    <p>I'm writing a simple game, and I have main frame with 4 JPanels placed in CardLayout. Main frame looks like that:</p> <pre><code>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); } </code></pre> <p>The GameScene panel have react to keyboard input. First I tried keylistener:</p> <pre><code>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"); } </code></pre> <p>That wasn't working... so I tried keybinding (simple implementation):</p> <pre><code>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); } }); } </code></pre> <p>It's still not working... I tried adding requestFocus and requestFocusInWindow() but with no effect. Any ideas how to fix it or to do it?</p> <p>Solution have been found. In key binding I should write:</p> <pre><code>getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(key, "pressed"); </code></pre> <p>insted of:</p> <pre><code>getInputMap().put(key, "pressed"); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload