Is it possible to clear a listener that I put on my JPanel
? When I call a method, I put a KeyListener
on the panel but when I quit this method, I want to clear that listener.
Here is my method :
private void stopBall(final Graphics2D g2, int posBallY, String winner) {
move = false;
scorePanel.showPressSpace(true);
setFocusable(true);
requestFocus();
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_SPACE){
setPosX(getPlayPanelWidth()/2);
setPosY(0);
move = true;
scorePanel.showPressSpace(false);
initBall(g2);
}
}});
if (winner == "player1") {
scoreCountPlayer1++;
scorePanel.getLab_Player1().setText("" + scoreCountPlayer1);
} else if (winner == "comp") {
scoreCountComputer++;
scorePanel.getLab_Computer().setText("" + scoreCountComputer);
}
}
You can set up a Timer for one second, and when you need to stop receiving key events, just disable the component by setEnabled(false) , then start the timer, and when it runs out, you call setEnabled(true) .
The KeyListener interface is found in java. awt. event package, and it has three methods.
You have an unqualified call to addKeyListener(KeyListener), so I presume that you've extended JPanel. If so, then you can call removeKeyListener(KeyListener). In your current code, your key listener is anonymous. You'll need to change it just a bit to hold on to that reference, like so:
// Create a variable holding the listener
KeyAdapter keyAdapter = new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_SPACE)
{
setPosX(getPlayPanelWidth() / 2);
setPosY(0);
move = true;
scorePanel.showPressSpace(false);
initBall(g2);
}
}
};
// Register the listener with this JPanel
addKeyListener(keyAdapter);
// Time passes...
// Remove the listener from this JPanel
removeKeyListener(keyAdapter);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With