0

For educational purposes, I am building a MIDI piano applet in Java. For that I want to:

  1. Capture key presses and releases
  2. Calculate the time between the same key's press and release.

What is the best way to implement key listener satisfying the above criteria?

Having only two key listeners (for key press and release) or having key listener per key?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Rumesh Madhusanka
  • 1,105
  • 3
  • 12
  • 26
  • Well.. what about this post? https://stackoverflow.com/questions/18037576/how-do-i-check-if-the-user-is-pressing-a-key – ymz Oct 27 '18 at 18:44

1 Answers1

1

Having only two key listeners (for key press and release) or having key listener per key?

Neither. I think you need a single listener that handles both key press and key release events ... for all of the keys. Each event includes a when attribute that you can use to compute how long a key was held down.

Finally, note that applets are now deprecated technology, so the educational value of doing this is limited, as is the practical value of the code you write. Most browsers removed all Java plugin / applet support some time ago.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Inside the Applet Class's init() function, addKeyListner(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { System.out.println("Time: "+e.getWhen()); System.out.println(e.getKeyText(e.getKeyCode())); } });`but when I hold down a key it seems to be multiple key stokes are generated instead of sustaining a single key press. – Rumesh Madhusanka Oct 28 '18 at 05:38
  • They are key events not key strokes. You need to filter them in your listener code. – Stephen C Oct 28 '18 at 06:26