One way to do this is to save the last key pressed into a field. Then, if the current key pressed is the same as the last key pressed, don't do anything. On a key up, clear the field.
Here's some example code:
package com.sandbox;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
public class SwingSandbox {
private static Character lastKey = null;
public static void main(String[] args) throws IOException {
JFrame frame = buildFrame();
frame.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
if (lastKey == null || lastKey != e.getKeyChar()) {
lastKey = e.getKeyChar();
System.out.println("keyTyped: " + lastKey);
}
}
@Override
public void keyPressed(KeyEvent e) {
if (lastKey == null || lastKey != e.getKeyChar()) {
lastKey = e.getKeyChar();
System.out.println("keyPressed: " + lastKey);
}
}
@Override
public void keyReleased(KeyEvent e) {
lastKey = null;
System.out.println("keyReleased");
}
});
}
private static JFrame buildFrame() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
return frame;
}
}
Despite what @schmop's comment says, I'm not experiencing that. With this code:
package com.sandbox;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
public class SwingSandbox {
public static void main(String[] args) throws IOException {
JFrame frame = buildFrame();
frame.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
System.out.println("keyTyped");
}
@Override
public void keyPressed(KeyEvent e) {
System.out.println("keyPressed");
}
@Override
public void keyReleased(KeyEvent e) {
System.out.println("keyReleased");
}
});
}
private static JFrame buildFrame() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
return frame;
}
}
This holding down a key prints this:
keyPressed keyTyped keyPressed keyTyped keyPressed keyTyped keyPressed
keyTyped keyPressed keyTyped keyPressed keyTyped keyPressed keyTyped
keyPressed keyTyped keyPressed keyTyped keyPressed keyTyped keyPressed
keyTyped keyPressed keyTyped keyPressed keyTyped keyPressed keyTyped
keyPressed keyTyped keyPressed keyTyped keyPressed keyTyped keyPressed
keyTyped keyPressed keyTyped keyPressed keyTyped
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…