I am creating a track and field game and I need the player to tap the button to fill the meter up. When the player releases the key the meter goes down. Unfortunately, when I hold the button the meter fills up.
Code:
public class TapGame extends JPanel implements ActionListener, KeyListener{
Timer tm = new Timer(5,this);
int barHeight = 0, bar = 0;
boolean canPress = true;
public TapGame(){
tm.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillRect(0, 355, bar, 10);
g.setColor(Color.WHITE);
g.drawRect(0, 355, 100, 10);
}
public void actionPerformed(ActionEvent e){
bar+= barHeight;
bar -= 2;
if (bar < 0) bar = 0;
if (bar > 98) bar = 98;
repaint();
}
public void keyPressed(KeyEvent e){
int c = e.getKeyCode();
if (c == KeyEvent.VK_A){
if (canPress) {
barHeight = 4;
canPress = false;
}
else barHeight=0;
}
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e){
canPress = true;
barHeight =0;
}
public static void main(String[] args){
TapGame t = new TapGame();
JFrame jf = new JFrame("Tap Mini Game Test");
jf.setSize(600,400);
jf.setLocationRelativeTo(null);
jf.setVisible(true);
jf.add(t);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
It appears java calls those button presses multiple times. See here: https://stackoverflow.com/questions/5199581/java-keylistener-keypressed-method-fires-too-fast
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.