简体   繁体   English

如何在不同的线程中使用keylistener?

[英]How to use keylistener in different thread?

I want to have input operations in different thread, what should i write into run method? 我想在不同的线程中进行输入操作,我应该写什么到run方法中? 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. 此代码应检测键事件,然后取决于键代码调用startMove()或endMove()函数。 And that all should be in the same thread. 并且所有这些都应该在同一线程中。 Should i use while loop into run and then somehow put there functions? 我应该使用while循环运行然后以某种方式放置那里的功能吗?

I think your design is "upside" down. 我认为您的设计是“颠倒”的。

First of all, UI events always come down to you in the AWT event dispatcher thread . 首先,UI事件总是AWT事件分派器线程中归结到您。

And what your code is doing: changing the speed of for some Player object. 代码的作用是:更改某些Player对象的速度。 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; 在该线程中运行的代码只需检查speed字段的值即可。 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. 并且根据这些鼠标事件改变的速度,使该类之外的其他代码“执行其操作”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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