-
Key Binding problem
I need to execute some code whenever the user presses the F1 key irrespective of which sub-component of the main frame has current focus and decided to go with key binding to implement the above situation.
For registering the keystroke F1 to the main frame of my swing application,
I tried out the following code:
Code:
JFrame mainFrame = new JFrame("MyApp");
Action action = new AbstractAction() {
public void actionPerformed(ActiomEvent actionEvent) {
System.out.println("F1 pressed");
}
};
String keyStrokeAndKey = "F1";
KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0);
mainFrame.getRootPane().getInputMap().put(keyStroke, keyStrokeAndKey);
mainFrame.getRootPane().getActionMap().put(keyStrokeAndKey, action);
Yet, on execution, the application does not respond to the F1 key.
Is there something inherently wrong with the above code? Thanks.
-
Not sure if this will help, but you can try adding a JPanel to the JFrame and adding the key stroke to JPanel instead.
-
You may need to use one of the other input maps. Have you tried passing an int condition parameter when you call getInputMap?