user3844143
user3844143

Reputation:

keyListener and thread not working

Hey I'm trying to have the console print out "holding" when a key is being held. I'm using an applet because this code is to test key holding in applets. if any someone with good java knowledge can explain to me whats going on it will be much appreciated.

I'm pretty sure that the problem might have something to do with the thread.

public class appletkeytest extends Applet implements KeyListener, Runnable {

    boolean held;

    public void init(){
        addKeyListener(this);
        Thread t = new Thread( this );
        t.start();
    }

    public void keyTyped(KeyEvent e) {
    }

    public void keyPressed(KeyEvent e) {
        held = true;
        System.out.println(held);
    }

    public void keyReleased(KeyEvent e) {   
        held = false;
        System.out.println(held);
    }

    public void run() {
        System.out.println(held);

        while(held){
            System.out.println("holding");
        }   
    }
}

Upvotes: 2

Views: 1406

Answers (1)

RealSkeptic
RealSkeptic

Reputation: 34638

First, I'd advise defining held as volatile.

Second, since you start the thread from the init() method, it will start running before you ever pressed the key, and thus finish right away.

I'd leave init like this:

public void init() {
    addKeyListener(this);
}

And change the keyPressed listener to:

public void keyPressed(KeyEvent e) {
    boolean wasHeld = held;
    held = true;
    System.out.println(held);
    if ( !wasHeld) {
        Thread t = new Thread(this);
        t.start();
    }
}

The reasoning behind the wasHeld variable is that when you hold down a key, it actually sends multiple keyPressed events until it is released. If you just created a thread for each of these, you'll have many threads created during one key holding, all of them busily writing to your console.

So you want to create the thread only if this is the first time the keyPressed event was sent for this particular key press. A new thread will be created when you press a key again after releasing the previous one.

Upvotes: 1

Related Questions