Skip to content
Advertisement

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement