1

I'm trying to set up a KeyListener to fire on KeyPressed and KeyReleased.

When I hold down a key, released if fired immediately after pressed, for example, if I hold down a key I get this output from a print statement on each event:

Pressed Released Pressed Released Pressed Released Pressed Released

Here is my KeyListener

import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;


public class EventListener extends JFrame implements KeyListener {

    public EventListener() {
        super();
        setSize(new Dimension(200, 300));
        addKeyListener(this);
        setVisible(true);

    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
        System.out.println("Pressed");
    }

    @Override
    public void keyReleased(KeyEvent e) {
        System.out.println("Released");
    }



  }

Does anyone have any idea what is happening?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Mark Provan
  • 1,041
  • 2
  • 13
  • 19
  • Sounds strange. I tested your code on MacOS X and it works fine. I pressed a key and hold it down for a few seconds and release it, the program print "Pressed" and "Released". – ntalbs Feb 07 '13 at 15:03
  • I believe that us a Unix behaviour. On Windows you will see Pressed, Pressed, Pressed, Pressed....Released. This is the way different Operating Systems generated events. There is no way to change this behaviour. – camickr Feb 07 '13 at 16:38
  • duplicate of http://stackoverflow.com/questions/1736828/how-to-stop-repeated-keypressed-keyreleased-events-in-swing – mdewitt Feb 08 '14 at 01:09

1 Answers1

2

The KeyEvents are registered natively. System-by-system that will change. Windows and Macs use a 'repeater delay', it resends the keyPressed event every n milliseconds based off of the repeater amount. Ubuntu bypasses this and just resends a new event instead of resending the same one.

It should have little-to-no effect on your program, depending on what happens when released.