Lord_Squirrel
Lord_Squirrel

Reputation: 1

Can't receive keyboard input in Java

I am trying to get some basic keyboard input functionality like the arrow keys. However, nothing i try seems to work, i've been using the KeyListener interface, the JPanel that checks for input gets the focus, and there seem to be no errors.

    public class PlayField extends JPanel implements KeyListener
    {
        private SpelModel mijnmodel;
        private boolean rechts = false;
        private boolean links = false;

        public PlayField(SpelModel mijnmodelArg)
        {
            setBackground(Color.WHITE); 
            mijnmodel = mijnmodelArg;
            this.setFocusable(true);
        }

        @Override
        public void paintComponent(Graphics g)
        {
            super.paintComponent(g); //some methods that i've taken out of the example
            drawStones(g,mijnmodel.getStenen());
            drawPeddle(g,mijnmodel.getBat());
            drawBall(g,mijnmodel.getBall()); 
        }
        @Override
        public void keyPressed(KeyEvent e){
            System.out.println("Key Pressed!!!");           
    }

    //Called when the key is released   
        @Override
    public void keyReleased(KeyEvent e){
        System.out.println("Key Released!!!");          
        }

        //Called when a key is typed
        @Override
        public void keyTyped(KeyEvent e){}
        }

Could the problem be that i am using multiple classes to create a window (first one JFrame, then one JPanel that includes 2 JPanels, whereof on is the "PlayField" class) and that the focus is impossible to achieve within another panel? What is the best course of action?

Upvotes: 0

Views: 700

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

Problems:

  • You have a class that implements KeyListener, but I don't see you adding a KeyListener to any component. Implementing the interface is not enough, but instead the KeyListener must be added to a component to do listening.
  • If you use KeyListeners, you must be careful with focus issues (as you've noted). The KeyListener only works if the component being listened to have focus.
  • KeyListeners should be avoided with Swing applications, and you're better off using Key Bindings. A brief search of this site will show you many discussions on this as this question has been asked and answered many times, more than several by me.
  • For example: java-keylistener-not-registering-arrow-keys

Upvotes: 6

Related Questions