The solution you are looking for is KeyBinding .
KeyBinding is the act of overwriting the operation of a keyboard key by associating it with a method to be executed every time it is pressed.
To apply KeyBiding
to your code, place 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 example above, I'm overwriting the behavior of your F2 key on the line that says inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0),"forward");
.
To make the KeyBinding with other keys replace the VK_F2
with the corresponding code. Examples:
VK_1: 1
VK_A: A
VK_EQUALS: =
Or see here all KeyEvent class attributes.
Within the actionPerformed()
method you write the code you want the new key behavior to be.
To trigger a button, use the doClick()
method of your reference variable.