954,523 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Hold Key Repeat Rate / Threads

Hi, in a Java Applet there the keys control movement, I have a couple of questions (sorry for the disorganized nature of multi-item requests).

1.

if (key=KeyEvent.VK_RIGHT)
{
    x++;
}


But, as you might have guessed by this post's title, the movement delays before continuing its motion, as a letter doesn't repeat while typing until you hold it down for a noticeable bit.

2. If I want something to just happen continually, like an artificial intelligence/gravity & physics, do I need a thread, or can I just place a while(True) loop in init() or start()?

My bountiful thanks!

YottaFlop
Newbie Poster
3 posts since Mar 2010
Reputation Points: 10
Solved Threads: 0
 

Edit: Sorry, I just noticed you were writing an applet. I'm not sure wether this works or not for applets

Hello!

As for your first problem with the keys, the only way I know to get around this is by keeping boolean flags of all interesting keys, alternatively keeping an array of booleans ranging from 0-256, then flagging the index corresponding to the ASCII-value of your pressed key.

Example:

boolean keyRight = false;

public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
        keyRight = true;
    }
}

public void keyReleased(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
        keyRight = false;
    }
}

private void move() {
    if (keyRight)
        x++;
}


As you can see from the code above I also introduced the procedure move(). Hence, we can move on to your next question. I would not use a "while(true)"-loop. Although this works, the clocking frequency will entirebly be dependent on your cpu speed, amount of calculations etc. If you are making a game this means that your game will run at different speeds on different systems.

My suggestion is that you add a timer to your project:

public class GameFrame extends JFrame implements ActionListener {

    // Timer(int timeMillis, ActionListener)
    private javax.swing.Timer timer = new javax.swing.Timer(10, this);

    public GameFrame() {
        timer.start();
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource().equals(timer)) {
            //This is where you calculate stuff
            move();
        }
    }
}


Good Luck!
Emil Olofsson

emilo35
Junior Poster
103 posts since Feb 2010
Reputation Points: 14
Solved Threads: 12
 

Thanks! That should port over fairly easily; I'll just check the API for a timer class.

YottaFlop
Newbie Poster
3 posts since Mar 2010
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: