簡體   English   中英

如何為多個JButton創建單個ActionListener

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

我正在使用MVC創建一個基本的計算器。 到目前為止,我正在改編一個教程,該教程僅將兩個用戶輸入的值加在一起。

目前,我要添加到視圖中的每個按鈕都有其自己的偵聽器,可以。 但是,根據本教程的控制器每個按鈕只有一個ActionListener內部類。 這重復了大量代碼。

如何為所有按下的按鈕創建一個ActionListener類,並在按下的按鈕的ID上使用case語句?

在視圖中注冊oneButton

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

在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");              
        }           
    }
}

從實現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 ...

    }
}

最好定義此類可以處理的動作命令是常量,從而消除任何歧義...

接下來,在保存按鈕的類中,創建ActionListener的實例。

CalculatorHandler handler = new CalculatorHandler();

然后像往常一樣創建按鈕並注冊handler ...

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

恕我直言,這種方法的唯一問題是它可以創建一個怪異的if-else語句,這可能變得難以維護。

在我看來,我將創建一種包含一系列輔助方法(例如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