Use of KeyListener with Thread

3.4k Views Asked by At

I want to move two objects at the same time. I want to use Thread for this. But it gives an error in the run method. How can I do this? How can I do this using keyboard events Like 2-player games?

Here's the code:

public class First extends JPanel implements Runnable,KeyListener{
    int y1=303/2;
    private int vy=0;

    public void paintComponent(Graphics g){
        g.setColor(Color.BLUE);
        g.fillRect(10,y1, 15, 20);
    }

    public void setVelocity(int v){
        vy=v;

    }

    @Override
    public void run() {
        int keyCode=e.getKeyCode();
        if(keyCode==KeyEvent.VK_UP ){

        }
        if(keyCode==KeyEvent.VK_S){

        }

        else if(keyCode==KeyEvent.VK_DOWN){

        }
        else if(keyCode==KeyEvent.VK_W){

        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
    public static void main(String[] args){
        JFrame jf=new JFrame();
        Panel p=new Panel();
        jf.add(p);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        jf.setSize(300,300);
        jf.setVisible(true);
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {

    }

    @Override
    public void keyReleased(KeyEvent e) {

    }
}

class Second extends JPanel{
    int y2=303/2;
    private int vy=0;

    public void setVelocity(int v){
        vy=v;

    }

    @Override
    public void paintComponent(Graphics g){
        g.setColor(Color.YELLOW);
        g.fillRect(150,y2, 15, 20);
    }

}

class Panel extends JPanel{
    First f=new First ();
    Second s=new Second();
    public void paintComponent(Graphics g){
        s.paintComponent(g);
        f.paintComponent(g);
    }
}
1

There are 1 best solutions below

0
On BEST ANSWER

How can I do this using keyboard events Like 2-player games?

An event is only generated for the last key pressed, so basically you need to track all the keys pressed (and when they are released).

I've done this in the past using Key Bindings with a Swing Timer.

Check out the KeyboardAnimation example found in Motion Using the Keyboard for a working example of this approach.

The link will also explain what Key Bindings are and why they should be preferred over a KeyListener.