The solution you seek is the Keybinding.
Keybinding is the act of overriding the operation of a keyboard key associating to it a method to be executed every time that key is pressed.
To apply the KeyBiding
in your code, put the following snippet inside the constructor of your class that extends Jframe:
InputMap inputMap = this.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0),"forward");
this.getRootPane().setInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW, inputMap);
this.getRootPane().getActionMap().put("forward", new AbstractAction(){
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("F2 foi pressionado");
btnExibir.doClick();
}
});
In the above example, I am overwriting the behavior of your key F2 in the line that says inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0),"forward");
.
To make the Keybinding with other keys replace the VK_F2
by the corresponding code. Examples:
VK_1: 1
VK_A: To
VK_EQUALS: =
Or see here all attributes of the Keyevent class.
Within the method actionPerformed()
you write the code you want to be the new key behavior.
To press a button, use the method doClick()
of its reference variable.
I didn’t understand how to apply your solution to my problem. Can you give me more details? Where to encode this part? Along with the Jframe file? Where?
– L. WD
@Luke within his main() method is called some other method or a constructor? You have a method that has a creation of a
JFrame
within or its own class extends fromJFrame
?– Math
My own class extends:
javax.swing.JFrame
– L. WD
@Lucas, I changed the example for a class that extends Jframe, see if you have any questions.
– Math