3

I have the following code in a game I am programming:

public void keyReleased(KeyEvent e) {
    int key = e.getKeyCode();
    if (key == KeyEvent.VK_SPACE) {
        doIShoot = false;
    }
}

public void keyPressed(KeyEvent e) {
    int key = e.getKeyCode();
    if (key == KeyEvent.VK_SPACE) {
        shoot();
    }
}

public void shoot(){
    if(!doIShoot){
        doIShoot = true;
        // code that creates bullet
    }
}

It is intended that the player must press the button for every bullet, it shouldn't automatically shoot when he holds space. In Windows that works just fine, but in Ubuntu Linux, it doesn't. It seems that when i hold space, it will always execute keyReleased and keyPressed alternately.

Why is Ubuntu doing this, and how can I make it work?

Edit:

I just found this: How to stop repeated keyPressed() / keyReleased() events in Swing

Edit2:

A Solution: http://brunez.net63.net/tutorials/keypressfix/keypressfix.php

Community
  • 1
  • 1
Odin
  • 677
  • 3
  • 15
  • 3
    *"In Windows that works just fine, but in Ubuntu Linux, it doesn't."* No, Linux works just fine, only not the way you want. It is up to the OS as to whether to fire one key event per 'press and hold' or many. For Swing, typically use key bindings over the AWT based, lower level, `KeyListener`. See [How to Use Key Bindings](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) for details. – Andrew Thompson May 18 '13 at 13:39
  • 2
    1+ for your edit. It's good to see self-research for a solution. I also second @Andrew's recommendation to use Key Bindings in place of KeyListeners for *most* Swing applications (but not for all situations). – Hovercraft Full Of Eels May 18 '13 at 13:39
  • @AndrewThompson: then why is it commonly refered as the "Java repeated keypress bug"? And for the other question: Why is Linux doing that? It seems pretty stupid for me. Wouldn't it have been a better solution to provide keyReleased() and keyPressed() like in Windows and additionally provide a keyHold() function? – Odin May 18 '13 at 13:44
  • 1
    As to why Linux does this -- that's simply how Linux behaves. Who knows what motivation underlies this feature. It is because it is. – Hovercraft Full Of Eels May 18 '13 at 13:57
  • 2
    *"then why is it commonly refered as the "Java repeated keypress bug"?"* 'Being a moron' is a common problem. My standard answer for "Why do people do X?" is "Because people are idiots!". Once you know that, most of what happens in the world becomes easy to understand. – Andrew Thompson May 18 '13 at 14:17
  • I think that these events are repeatly fired in other OS too – mKorbel May 18 '13 at 14:46
  • @AndrewThompson I would argue that this is indeed a bug. Not with Linux, but with Java. Because Java is supposed to be platform independent. – rurouniwallace Jul 11 '13 at 21:20

0 Answers0