How to add action listener that listens to multiple buttons

后端 未结 11 1120
温柔的废话
温柔的废话 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:34

    I use "e.getActionCommand().contains(CharSecuence s)", since I´m coming from an MVC context, and the Button is declared in the View class, but the actionPerformed call occurs in the controller.

    public View() {
        ....
        buttonPlus = new Button("+");
        buttonMinus = new Button("-");
        ....
    }
    
    public void addController(ActionListener controller) {
        buttonPlus.addActionListener(controller);
        buttonMinus.addActionListener(controller);
    }
    

    My controller class implements ActionListener, and so, when overriding actionPerformed:

    public void actionPerformed(ActionEvent e) {
        if(e.getActionCommand().contains("+")) {
            //do some action on the model
        } else if (e.getActionCommand().contains("-")) {
           //do some other action on the model
        }
    }
    

    I hope this other answer is also useful.

提交回复
热议问题