Search code examples
javaswingjbuttonactionlistener

JButton with actionPerformed and keyReleased


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?


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);