Question

I have a JButton, I want it to do something when the button is pressed and I want it to do the same thing when a key is pressed, how do I do that?

Was it helpful?

Solution

To do something when a button is pressed you should add an ActionListener to that button like this:

JButton button = new JButton();
button.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub

    }
});

And to response to key pressed do something like this : (for example if user enters control alt 7)

Action actionListener = new AbstractAction() {
  public void actionPerformed(ActionEvent actionEvent) {
    JButton source = (JButton) actionEvent.getSource();
    System.out.println("Activated: " + source.getText());// just for test
  }
};
//.....

KeyStroke controlAlt7 = KeyStroke.getKeyStroke("control alt 7");
InputMap inputMap = button.getInputMap();
inputMap.put(controlAlt7, ACTION_KEY);
ActionMap actionMap = button.getActionMap();
actionMap.put(ACTION_KEY, actionListener);

OTHER TIPS

As far as I know (haven't messed with Swing in a couple of years...) the only key button events that can act upon a button are Tab which changes the element focus, Enter which fires the actionPerformed method and mnemonics, which also fire the actionPerformed.

To handle events on button clicks, you could do something like so:

 button.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e)
            {
                //Execute when button is pressed
            }
        });  

You may want to look into the Action API. You can see more at How to Use Actions. You can use the Action for buttons (works like an ActionListener) and you can add key shortcuts to it.

You can see this example where key shortcuts are added to the toolbar button as well as the menu items. The interesting thing you mat want to notice is the the menu item and the tool bar button share the same Action and thus do the same thing.

enter image description here

    JButton button = new JButton("Submit");
    //Add action listener to button
    button.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e)
        {
            //Execute when button is pressed
            //do your work here
            System.out.println("You clicked the submit button");
        }
    });      

This is how to use actionlistener with jbutton

Try this:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class EventedButtonExample extends JFrame {
    private JButton simpleButton;
    private static final long serialVersionUID = 42L;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                EventedButtonExample me = new EventedButtonExample();
                me.initialize();
                me.setVisible(true);
            }
        });
    }

    void initialize() {
        simpleButton = new JButton("I am an simple, evented button!");
        CompoundEventHandler eh = new CompoundEventHandler();
        simpleButton.addActionListener(eh);
        simpleButton.addKeyListener(eh);
        getContentPane().add(simpleButton, BorderLayout.CENTER);
        pack();
    }

    class CompoundEventHandler extends KeyAdapter implements ActionListener {
        public void keyReleased(KeyEvent e) {
            int keyCode = e.getKeyCode();
            System.out.println("Key pressed: " + keyCode + " (" + KeyEvent.getKeyText(keyCode) + ")");
        }

        public void actionPerformed(ActionEvent e) {
            System.out.println("A button is pressed!");
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top