How can I create a single ActionListener for multiple JButtons

后端 未结 2 734
别那么骄傲
别那么骄傲 2020-12-22 10:28

I\'m creating a basic calculator using MVC. So far I\'m adapting a tutorial which merely sums two user entered values together.

Currently each button I\'m adding to

2条回答
  •  忘掉有多难
    2020-12-22 11:09

    Start with class which implements ActionListener...

    public class CalculatorHandler implements ActionListener{
    
        public static final String ADD_ACTION_COMMAND = "Action.add";
    
        public void actionPerformed(ActionEvent e){
    
            if (ADD_ACTION_COMMAND.equals(e.getActionCommand()) {
                // Do your addition...
            } else if ...
    
        }
    }
    

    It's best to define the action commands that this class can handle is constants, thus removing any ambiguity...

    Next, in the class that holds the buttons, create an instance of the ActionListener...

    CalculatorHandler handler = new CalculatorHandler();
    

    Then create you buttons as per usual and register the handler...

    JButton plus = new JButton("+");
    plus.setActionCommand(CalculatorHandler.ADD_ACTION_COMMAND);
    plus.addActionListener(handler);
    

    The only problem with this approach, IMHO, is that it can create a monster if-else statement which may become difficult to maintain.

    To my mind, I'd create some kind of model/builder that contained a series of helper methods (like add(Number), subtract(Number) etc) and use Actions API for the individual actions for each button...but that's just me...

提交回复
热议问题