How to add action listener that listens to multiple buttons

后端 未结 11 1110
温柔的废话
温柔的废话 2020-11-27 04:25

I\'m trying to figure out what i am doing wrong with action listeners. I\'m following multiple tutorials and yet netbeans and eclipse are giving me errors when im trying to

11条回答
  •  感情败类
    2020-11-27 04:50

    There are good answers here but let me address the more global point of adding action listener that listens to multiple buttons.

    There are two popular approaches.

    Using a Common Action Listener

    You can get the source of the action in your actionPerformed(ActionEvent e) implementation:

    JButton button1, button2; //your button
    
    @Override
    public void actionPerformed(ActionEvent e) {
    
        JButton actionSource = (JButton) e.getSource();
    
        if(actionSource.equals(button1)){
            // YOU BUTTON 1 CODE HERE
        } else if (actionSource.equals(button2)) {
            // YOU BUTTON 2 CODE HERE
        }
    }
    

    Using ActionCommand

    With this approach you setting the actionCommand field of your button which later will allow you to use switch:

    button1.setActionCommand("actionName1");
    button2.setActionCommand("actionName2");
    

    And later:

    @Override
    public void actionPerformed(ActionEvent e) {
        String actionCommand = ((JButton) e.getSource()).getActionCommand();
    
        switch (actionCommand) {
            case "actionName1": 
                // YOU BUTTON 1 CODE HERE
            break;
            case "actionName2": 
                // YOU BUTTON 2 CODE HERE
            break;
        }
    }
    

    Check out to learn more about JFrame Buttons, Listeners and Fields.

提交回复
热议问题