1

I'm making a game and I am wondering how you add a keylistener to a jpanel (How to get key input from the user without using a textfield or textarea or anything like that)?

I'm using the timer class (javax.swing.timer), and in the constructor of my own class that I made, I typed:

addKeyListener(new KeyAdapter(){
        @Override
        public void keyPressed(KeyEvent e){
            int key=e.getKeyCode();

            if(key==KeyEvent.VK_DOWN){
                y+=movey;
            }
        }

        @Override
        public void keyReleased(KeyEvent e){

        }

        @Override
        public void keyTyped(KeyEvent e){

        }
    });

It doesn't work with this code for some reason. Any suggestions? It doesn't matter what key is being hit, I just want to know how to add a keylistener to the JPanel.

Thanks

  • Read up on the similar questions on this site first please. Don't use a KeyListener for this, use Key Bindings. – Hovercraft Full Of Eels Feb 08 '15 at 04:02
  • @HovercraftFullOfEels I am not wondering how to make the code depending if more than one key is pressed at the same time. I am wondering just simply how to add a key listener to the JPanel in the first time. I know it is possible because I have seen it done before. – Michael Sinclair Feb 08 '15 at 04:18
  • 2
    The best answer though still is: don't do it. Even Oracle, the over-seers of Java will tell you this. – Hovercraft Full Of Eels Feb 08 '15 at 04:20

0 Answers0