How would I fix this bug?
Not really a bug as much as incompatiblity.
If there is an alternative to KeyListener that will do the same thing, please let me know and preferably provide an example of how it would work.
Dont use KeyListener
/KeyAdapter
for Swing components as there is focus issues, which can be gotten around by calling requestFocusInWindow()
on the component after its visible to make sure it has focus and of course setFoucsable(true);
must be called if component is not focusable like a JLabel
.
Swing components should use KeyBinding
s, which overcomes the above mentioned problems by automatically calling setFocusable(true)
on the component to which KeyBinding
is added etc.
Here is a small example:
void addKeyBinding(JComponent jc) {
jc.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, false), "A pressed");
jc.getActionMap().put("esc pressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
System.out.println("A pressed");
}
});
jc.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, true), "A released");
jc.getActionMap().put("A released", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
System.out.println("A released");
}
});
}
you would call this method with the instance of the JComponent
i.e JPanel
etc that you want to add the Keybinding
too:
JPanel p=new JPanel();
addKeyBinding(p);
Other suggestions on code:
Always create Swing components on
Event Dispatch Thread
viaSwingUtilities.invokeXXX
blockDont implement an
Listener
likeActionListener
on the class itself unless this class will be used as aListener
only, or you want to expose the implementing classes/Listeners
methods to other classes.