简体   繁体   English

如何为多个JButton创建单个ActionListener

[英]How can I create a single ActionListener for multiple JButtons

I'm creating a basic calculator using MVC. 我正在使用MVC创建一个基本的计算器。 So far I'm adapting a tutorial which merely sums two user entered values together. 到目前为止,我正在改编一个教程,该教程仅将两个用户输入的值加在一起。

Currently each button I'm adding to the view has it's own listener, which is ok. 目前,我要添加到视图中的每个按钮都有其自己的侦听器,可以。 However, the controller as per the tutorial has a single ActionListener inner class per button. 但是,根据本教程的控制器每个按钮只有一个ActionListener内部类。 This repeats a huge amount of code. 这重复了大量代码。

How can I create a single ActionListener class for all buttons pressed, and use a case statement on the id of the button pressed? 如何为所有按下的按钮创建一个ActionListener类,并在按下的按钮的ID上使用case语句?

Registering the oneButton in the View 在视图中注册oneButton

void oneListener(ActionListener listenForOneButton){    
    oneButton.addActionListener(listenForOneButton);
}    

Implementing the ActionListener for the oneButton in the Controller inner class 在Controller内部类中为oneButton实现ActionListener

class oneListener implements ActionListener{
    public void actionPerformed(ActionEvent e){
        int previousNumber, displayNumber = 0;          
        try{
            previousNumber = theView.getPreviousDisplayNumber();
            displayNumber = previousNumber+1;               
            theView.setDisplayNumber(displayNumber);
        }           
        catch(NumberFormatException ex){                
            System.out.println(ex);             
            theView.displayErrorMessage("You Need to Enter Integers");              
        }           
    }
}

Start with class which implements ActionListener ... 从实现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 ... 接下来,在保存按钮的类中,创建ActionListener的实例。

CalculatorHandler handler = new CalculatorHandler();

Then create you buttons as per usual and register the handler ... 然后像往常一样创建按钮并注册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. 恕我直言,这种方法的唯一问题是它可以创建一个怪异的if-else语句,这可能变得难以维护。

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... 在我看来,我将创建一种包含一系列辅助方法(例如add(Number)subtract(Number)等)的模型/构建器,并为每个按钮的各个操作使用Actions API ...但这就是只有我...

public class SingleActionListener implements ActionListener {
    public void initializeButtons() {
        JButton[] buttons = new JButton[4];
        String[] buttonNames = new String[] {"button1", "button2", "button3", "button4"};

        for (int i = 0; i < 4; i++) {
            buttons[i] = new JButton(buttonNames[i]);
        }
    }

    public void addActionListenersToButtons() {
        for (int i = 0; i < 4; i++) {
            buttons[i].addActionListener(this);
        }
    }

    public void actionPerformedd(ActionEvent actionEvent) {
        if (actionEvent.getSource() == buttons[0]) {
            //Do required tasks.
        }

        if (actionEvent.getSource() == buttons[1]) {
            //Do required tasks.
        }

        if (actionEvent.getSource() == buttons[2]) {
            //Do required tasks.
        }

        if (actionEvent.getSource() == buttons[3]) {
            //Do required tasks.
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM