簡體   English   中英

防止用戶在Eclipse中按住鍵

[英]Prevent User from holding key down in Eclipse

我正在創建一個田徑游戲,我需要玩家點擊按鈕以填充儀表。 當播放器釋放鍵時,儀表關閉。 不幸的是,當我按住按鈕時,儀表已滿。

碼:

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

}
}

看來Java多次調用了這些按鈕。 看到這里: https : //stackoverflow.com/questions/5199581/java-keylistener-keypressed-method-fires-too-fast

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM