This is a follow-up question to my previous question. I got my key holding to move, using boolean
variables and making another method with a javax.swing.Timer
for delays(Thank you to KingDolphin), but strangely when I move my Icon it seems to increase how many pixels it moves each time by 1. It moves one pixel the first keyPressed
, then two for the next, then three, etc. This may not seem like much, but when you are moving by 30+ pixels, it gets out of control. I really have no Idea how to fix it. I have tried changing some things, and I have "done my homework"(Googled and searched StackExchange sites including this one and StackOverflow), but have found nothing even related to it. Here's my layoutGame
and move
methods(The problem is in there), and thank you for helping me out:
private void layoutGame() {
JLabel title = new JLabel("Dodge The Enemies!");
Font titleFont = new Font(Font.SERIF, Font.BOLD, 32);
title.setFont(titleFont);
title.setHorizontalAlignment(JLabel.CENTER);
title.setBackground(Color.BLACK);
title.setForeground(Color.WHITE);
title.setOpaque(true);
add(title, BorderLayout.NORTH);
JLabel background = new JLabel();
background.setIcon(backDrop);
add(background, BorderLayout.CENTER);
JLabel you = new JLabel();
you.setBounds(x, y, 50, 50);
you.setIcon(new ImageIcon(this.getClass().getClassLoader().getResource("happy.png")));
background.add(you, JLabel.CENTER);
JTextPane direction = new JTextPane();
direction.setText("Direction");
add(direction, BorderLayout.SOUTH);
direction.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyChar() == 'w') {
wPressed = true;
move(you);
} else if (e.getKeyChar() == 'a') {
aPressed = true;
move(you);
} else if (e.getKeyChar() == 's') {
sPressed = true;
move(you);
} else if (e.getKeyChar() == 'd') {
dPressed = true;
move(you);
}
direction.setText(null);
}
public void keyReleased(KeyEvent e) {
wPressed = false;
aPressed = false;
sPressed = false;
dPressed = false;
}
});
}
private void move(JLabel icon) {
int delay = 100; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (wPressed) {
y = y - 1;
} else if(aPressed) {
x = x - 1;
} else if(sPressed) {
y = y + 1;
} else if(dPressed) {
x = x + 1;
}
icon.setBounds(x, y, 50, 50);
icon.repaint();
}
};
new Timer(delay, taskPerformer).start();
}