connor.p
connor.p

Reputation: 866

Adding KeyListeners to JPanel not working

I've just completed an online tutorial on making a networked game. The game it's self is just a small circle that follows the mouse when on the screen.

I've been modifying the code to use keys to move the circle instead of the mouse. However whilst I've done this before I've never used “JPanel” and I’m struggling to get the keys to move the circle around.

The game's 'client' side only consists of two files, Client.java and DataPackage.java, the problem (to my knowledge) appears to be in Client.java.

I wont paste the whole code as it is quite big (i will if you think it is necessary), but here is the bit that makes the ball follow the mouse

public Client()
    {
        this.addMouseMotionListener(new MouseMotionListener()
        {

            @Override
            public void mouseDragged(MouseEvent e)
            {
                x = e.getX();
                y = e.getY();
            }

            @Override
            public void mouseMoved(MouseEvent e) {}

        });
}

now I've tried just changing

this.addMouseMotionListener(new MouseMotionListener()
            {

                @Override
                public void mouseDragged(MouseEvent e)
                {
                    x = e.getX();
                    y = e.getY();
                }

                @Override
                public void mouseMoved(MouseEvent e) {}

            });

to

this.addKeyListener(new KeyListener() {
            public void keyPressed(KeyEvent e) { System.out.println( "tester"); }

            public void keyReleased(KeyEvent e) { System.out.println("2test2"); }

            public void keyTyped(KeyEvent e) { System.out.println("3test3"); }
        });

but this didn't appear to work, then i tried changing the location of the keying code by putting it outside of the

public Client() { }

Then I thought it could be the 'implements' tags at the top of the file. so I added

implements KeyListener

to the end of

public class Client extends JComponent

but again, this did not work then I did some more research and it seems that I need to set the panel to be focused by using

panel.setFocusable(true);

but the source of this information, failed to say where to put it and everywhere I put it throws an error

Can someone shed some light on this for me please?

Upvotes: 2

Views: 153

Answers (1)

nachokk
nachokk

Reputation: 14413

Take a look of @camickr ,a swing guru, article Motion using the keyboard. Using KeyListeners has 2 big issues, components must be focusable and have to be in focus.KeyBindings is the proper way to do in swing, bind a key to a particular action. How to Use KeyBindings

Upvotes: 4

Related Questions