Julian E.
Julian E.

Reputation: 19

Having Listener in new Thread

I'm trying to place my KeyListener in a new Thread called Keys in my project because my main thread is already in a loop. So I want this method to return a boolean if the key is pressed or not. I'm pretty new to Java so sorry if that is just a dumb mistake.

Thread:

public class Keys implements KeyListener, Runnable {

    private boolean w = false;
    //private boolean ... same stuff

    public void keyTyped(KeyEvent keyEvent) {
        //nothing in here ;)
    }
    public void keyPressed(KeyEvent keyEvent) {
        //set right boolean true = no problem
    }
    public void keyReleased(KeyEvent keyEvent) {
        //set right boolean false = no problem
    }

    public void run() {
        //nothing to do here
    }

    public boolean isWPressed(){
        return w;
    }
    //public boolean is...() [more of them.]
}

I would appreciate an example. That's the best way I learn.

Upvotes: 1

Views: 2849

Answers (2)

Turing85
Turing85

Reputation: 20195

The Listener is not called by your program. Swing calls the Listener when an apropiate event happens. For example: say we write a KeyListener for a TextField. If the user starts typing in this TextField, Swing will call the corresponding methods in the listener. So, the Listener is called by Swing, not by your code and thus you cannot write it for an own thread. This principle is also known as Hollywood principle ("Don't call us, we call you!") (wikipedia.org). This link gives a good introduction to Events and Listener in Swing.

EDIT

As mentioned by SJuan76, we are able to launch seperate threads FROM the listener to do stuff we want them to.

Upvotes: 2

Keval
Keval

Reputation: 1612

The Java Key Listener that you are using runs on it's own thread already. There is no need to try to put it in it's own thread.

Reading into the comments however, if you want to start a new thread when a key is pressed for example, you could. The following is how you might go about it:

Thread thread = new Thread(this, "Keyboard Thread");

Hope this helped!

Upvotes: 1

Related Questions