Alex
Alex

Reputation: 1073

Adding keylistener or key binding to JButtons that use ActionListener

i need some help with adding keylistener or key bindings to the buttons from the next example. I want when i press A or B on the keyboard, to make the same action like when i press it with the mouse.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class NetTest {

    static JButton btnA = new JButton("A");
    static JButton btnB = new JButton("B");
    static JPanel jp = new JPanel();
    static JFrame jf = new JFrame("Test APP");
    static JLabel jl = new JLabel("Which button was clicked ?");

    static ActionListener action = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            jl.setText(((JButton)e.getSource()).getText());
        }
    };

    public static void main(String[] args) {
        jf.setVisible(true);
        jf.setSize(400, 400);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        jp.add(btnA);
        jp.add(btnB);
        jp.add(jl);
        jf.add(jp);

        btnA.addActionListener(action);
        btnB.addActionListener(action);
    }
}

Upvotes: 2

Views: 21290

Answers (2)

Polentino
Polentino

Reputation: 907

If I understood what you want to achieve, basically you want to listen for two specific keyboards events ( key "A" or "B" pressed ), and toggle the label as if you clicked one of the two JButton.

You simply need to add a KeyListener to your frame, and implement its callbacks to respond to "A" or "B" typed only. Also remember to call setFocusable(false) on your JFrame object

    jf.setFocusable(true);
    jf.addKeyListener( new KeyListener() {

        @Override
        public void keyTyped( KeyEvent evt ) {
        }

        @Override
        public void keyPressed( KeyEvent evt ) {
        }

        @Override
        public void keyReleased( KeyEvent evt ) {
        }
    } );

Upvotes: 2

dic19
dic19

Reputation: 17971

In order to listen to KeyEvents you need to use JComponent#getInputMap() and JComponent#getActionMap() methods to put the input event you want to listen and the correspondent action. Try this example:

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Demo{

    private void initGUI(){
        AbstractAction buttonPressed = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println(e.getActionCommand());
            }
        };

        JButton submit = new JButton("Submit");
        submit.addActionListener(buttonPressed);

        /*
         * Get the InputMap related to JComponent.WHEN_IN_FOCUSED_WINDOW condition
         * to put an event when A key is pressed
         */
        submit.getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).
                put(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A,0), "A_pressed");
        /*
         * Add an action when the event key is "A_pressed"
         */
        submit.getActionMap().put("A_pressed", buttonPressed);

        /*
         * Same as above when you press B key
         */
        submit.getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).
                put(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_B,0), "B_pressed");
        submit.getActionMap().put("B_pressed", buttonPressed);

        JPanel content = new JPanel(new FlowLayout());
        content.add(new JLabel("Test:"));
        content.add(submit);

        JFrame frame = new JFrame("Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(content);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Demo().initGUI();
            }
        });

    }
}

Note: this example uses the same AbstractAction when the JButton or A/B keys are pressed, but the output will depend on who is the event source.

Note 2: if you use JComponent.WHEN_IN_FOCUSED_WINDOW condition your action will be executed anytime keys A or B are pressed. This behavior is not desired when you have text input components such as JTextfield or JTextArea and final user almost sure will press A or B keys many times. If that is the case then you'll have to use JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT condition.

Upvotes: 3

Related Questions