addKeyListener() doesn't work for JPanel

后端 未结 2 1649
小蘑菇
小蘑菇 2020-11-27 19:08

I am trying to make a game engine. I have made the Game class but the error resides in the KeyBoard class. Here I leave some code.

Class:: Game



        
相关标签:
2条回答
  • 2020-11-27 19:39

    Simply, your panel needs to be focusable. Add in wherever you create the panel:

    panel.setFocusable(true);
    panel.requestFocusInWindow();
    

    Here's a SSCCE (I suggest asking questions with one of these in the future):

    import java.awt.Dimension;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    
    public class SimpleKeyTest {
    
        public static void main(String[] args) {
    
            Runnable r = new Runnable() {
    
                @Override
                public void run() {
                    JFrame frame = new JFrame();
                    JPanel panel = new JPanel();
    
                    frame.getContentPane().add(panel);
    
                    panel.addKeyListener(new KeyListener() {
    
                        @Override
                        public void keyTyped(KeyEvent e) {}
    
                        @Override
                        public void keyReleased(KeyEvent e) {}
    
                        @Override
                        public void keyPressed(KeyEvent e) {
                            System.out.println("Pressed " + e.getKeyChar());
                        }
                    });
    
                    panel.setFocusable(true);
                    panel.requestFocusInWindow();
    
                    frame.setSize(new Dimension(300, 300));
                    frame.setVisible(true);
                }
    
            };
    
            SwingUtilities.invokeLater(r);
    
        }
    }
    

    Also, https://www.google.com/search?q=jpanel+keylistener

    0 讨论(0)
  • 2020-11-27 19:58

    You can add the key listener to the JFrame, that's something I've done in the past. It's probably not a good idea however if you have other components in the JFrame.

    0 讨论(0)
提交回复
热议问题