Vaughan Hilts
Vaughan Hilts

Reputation: 2879

Adding global keybinding for JButtons?

I have:

    for (int i = 0; i <= 9; i++) {
        JButton c = new JButton();
        c.setText(Integer.toString(i));
        ActionListener l = new NumericButtonListener(i);
        c.addActionListener(l);
        buttonGrid.add(c); }

So basically, some code that creates a grid of numbers. How can I map my pane to allow hitting the appropriate number and trigger my NumericButtonListener?

Upvotes: 1

Views: 125

Answers (2)

Sage
Sage

Reputation: 15408

  1. You can use keyBindings and assign one common Action for the specific key.

  2. Make use of button's doClick() function to generate an Action event and listens to it. You will need to invoke this function on the specific button to which mapped key is pressed. For example:

    Action generateClick = new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
          JButton butt = (JButton) e.getSource();
          butt.doClick();
      }
     };
    

Upvotes: 2

alex2410
alex2410

Reputation: 10994

Use keyBinding for each button. See tutorial for KeyBindings

For example add next code in creation:

c.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(Integer.toString(i)), "doSomething");
c.getActionMap ().put("doSomething", new AbstractAction() {

      @Override
      public void actionPerformed(ActionEvent arg0) {
            System.out.println(c.getText());
      }  
});

Upvotes: 0

Related Questions