I've a frame with a text field, a table and two buttons!
I would like to add a KeyListener to listen when a modifier key is pressed and released, in order to change the text of the Ok button and let user select different methods. The listener should work regardless which component is in focus.
For example:
- No modifiers: "Ok" - Do Something;
- Shift key pressed: "Ok and close" - Do Something and close the frame;
- Alt key pressed... etc
Right now I've found this solution, but it seems a bit cluncky and not elegant at all.
public class MyFrame extends JFrame {
private boolean shiftPressed;
private MyDispatcher keyDispatcher;
public MyFrame () {
super();
initGUI();
shiftPressed = false;
KeyboardFocusManager currentManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
keyDispatcher = new MyDispatcher();
currentManager.addKeyEventDispatcher(keyDispatcher);
//...remain of code
}
@Override
public void dispose() {
// I remove the dispatcher when the frame is closed;
KeyboardFocusManager currentManager = KeyboardFocusManager
.getCurrentKeyboardFocusManager();
currentManager.removeKeyEventDispatcher(keyDispatcher);
super.dispose();
}
private class MyDispatcher implements KeyEventDispatcher {
@Override
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getModifiers() == KeyEvent.SHIFT_MASK) {
if (e.getID() == KeyEvent.KEY_PRESSED) {
System.out.println("Shift Pressed");
shiftPressed = true;
btnOk.setText("Ok and Close");
}
} else if (e.getID() == KeyEvent.KEY_RELEASED) {
if(!e.isShiftDown() && shiftPressed) {
System.out.println("Shift Released");
btnOk.setText("Ok");
}
}
return false;
}
}
}
Any suggestion on how to improve the code?