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