简体   繁体   中英

How to use keylistener in different thread?

I want to have input operations in different thread, what should i write into run method? Or may be it is a better way to do this?

public class Player implements Runnable, KeyListener{

    int speed;

    public Player() 
    {
        speed = 0;
    }

    @Override
    public void run()
    {       
        //what should i write here?
    }

    @Override
    public void keyTyped(KeyEvent e) {}

    @Override
    public void keyPressed(KeyEvent e) 
    {
        startMove(e);
    }

    @Override
    public void keyReleased(KeyEvent e) 
    {
        endMove(e);
    }   


       public void startMove(KeyEvent e)
    {        
        int key = e.getKeyCode();

        switch (key) {
            case KeyEvent.VK_W:
                speed = 2;
                break;
            case KeyEvent.VK_S:
                speed = -2;
                break;
            default:
                break;
        }
    }

    public void endMove(KeyEvent e)
    {
        int key = e.getKeyCode();

        if(key == KeyEvent.VK_W)
            speed = 0; 
        if(key == KeyEvent.VK_S)
            speed = 0;

    }   
}

This code should detect key events and then depends on key code call startMove() or endMove() functions. And that all should be in the same thread. Should i use while loop into run and then somehow put there functions?

I think your design is "upside" down.

First of all, UI events always come down to you in the AWT event dispatcher thread .

And what your code is doing: changing the speed of for some Player object. Where is there a need for another thread?

Meaning: you should already use some other "game controller thread". The code run in that thread simply checks the value of that speed field; and makes use of that.

The core thing is: your start/end methods just change a field; and that is fine. And you should keep it that way. And have other code outside of that class "do its thing" based on the speed changed by those mouse events.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM