阻止用户在Eclipse中按住键

时间:2014-01-11 22:03:38

标签: java keylistener

我正在创建一个田径游戏,我需要玩家点击按钮来填充米。当玩家释放钥匙时,仪表会下降。不幸的是,当我按下按钮时,仪表会充满。

代码:

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);

}
}

1 个答案:

答案 0 :(得分:0)