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!

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.