Push button by hotkey in Java

Asked

Viewed 8,155 times

6

I have a java application created by Netbean IDE 8.0.

In this application I created a Jframe and put a Jbutton, which when pressed displays a message.

private void btnExibirActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("O botão foi acionado!");
}

How to trigger this button via a keyboard shortcut (Example: F2)?

2 answers

7

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?

  • @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 from JFrame?

  • My own class extends: javax.swing.JFrame

  • @Lucas, I changed the example for a class that extends Jframe, see if you have any questions.

4

You can do it like this:

import java.awt.AWTEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JButton;
import javax.swing.JFrame;

@SuppressWarnings("serial")
public class TeclaAtalho extends JFrame {
    private JButton button;

    public TeclaAtalho() {
        button = new JButton("Click ou aperte F2");

        //ActionListener
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                buttonAction(e);
            }
        });

        //KeyListener para o Frame
        button.addKeyListener(new KeyListener() {

            //Quando soltar a tecla
            public void keyReleased(KeyEvent e) {

                //Se a tecla pressionada for igual a F2
                if (e.getKeyCode() == KeyEvent.VK_F2) 
                    buttonAction(e);
            }

            public void keyTyped(KeyEvent e) {}
            public void keyPressed(KeyEvent e) {}
        });

        add(button);

        setVisible(true);
        setSize(300, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    //Tanto a tecla de atalho quanto o click no botão
    //vai chamar esse método
    private void buttonAction(AWTEvent e) {
        if (e instanceof KeyEvent) {
            System.out.println("Chegamos aqui a partir da tecla de atalho");
        }

        else if (e instanceof ActionEvent) {
            System.out.println("Chegamos aqui a partir do click no botão (ou a tecla espaço)");
        }
    }

    //Método main
    public static void main(String[] args) {
        new TeclaAtalho();
    }
}
  • 1

    Hello @Igor, could you, in addition to posting the code, give an explanation about the solution? If you consider that someone else might have the same problem, you can also enjoy your answer. Any doubt you can make the [tour] and even the topic [Answer] of [help]

  • @The above mentioned code is a good example !!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.