Trigger button per shortcut key in Java

5

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 do you push this button through a keyboard shortcut (Example: F2)?

    
asked by anonymous 11.04.2014 / 01:27

2 answers

7

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.

    
11.04.2014 / 02:43
3

You can do 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();
    }
}
    
19.08.2014 / 18:45