使相同的一般JButton根据其子类做不同的事情

时间:2014-06-02 09:54:13

标签: java swing model-view-controller jbutton actionlistener

我有一个非常简单的银行账户,我是为了练习我的MVC知识而建立的。但是我遇到了麻烦。

由于存款和提款屏幕基本相同,我几乎将其全部抽象为BaseWindow类。

Deposit Window Withdraw Window

这是 BaseWindow 类:

public class BaseWindow extends JFrame {

    private static final long serialVersionUID = 4741220023341218042L;

    JButton executeButton;

    public BaseWindow(String title){
        super(title);
        JPanel panel = new JPanel(new GridLayout(0, 3));
        JLabel amountLabel = new JLabel("Amount: "); 
        JTextField inputBox = new JTextField(15);
        executeButton = new JButton("Execute");
        JLabel newBalanceLabel = new JLabel("New Balance: "); 
        JLabel newBalance = new JLabel();
        panel.add(amountLabel);
        panel.add(inputBox);
        panel.add(executeButton);
        panel.add(newBalanceLabel);
        panel.add(newBalance);
        panel.add(new JLabel()); //Empty, for layout purposes
        add(panel);
        pack();
    }

    public JButton getExecuteButton(){
        return executeButton;
    }
}

问题

由于我使用的是Model-View-Controller模式,Execute按钮的功能在Controller类中确定,该类由以下内容组成:

...
public void startDepositWindow(){
        DepositWindow depositWindow = view.createDepositWindow();
        depositWindow.getExecuteButton().addActionListener(createExecuteButtonListener());
        depositWindow.run();
    }
    public void startWithdrawWindow(){
        WithdrawWindow withdrawWindow = view.createWithdrawWindow();
        withdrawWindow.getExecuteButton().addActionListener(createExecuteButtonListener());
        withdrawWindow.run();
    }

    //Button Action Listeners
    private ActionListener createDepositButtonListener(){
        return new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                startDepositWindow();
            }
        };
    }
    private ActionListener createWithdrawButtonListener(){
        return new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                startWithdrawWindow();
            }
        };
    }
    private ActionListener createExecuteButtonListener(){
        return new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // WHAT GOES HERE??
            }
        };
    }

...

问题是,我无法想到createExecuteButtonListener中的内容,因为我不能简单地说model.deposit()model.withdraw(),因为我不知道执行哪个窗口里面点击了按钮。

据我所知,我不能在这里使用多态,因为监听器没有绑定在DepositWindowWithdrawWindow子类中,我不想在那里调用它们,因为那样会违反了模型 - 视图 - 控制器。

所以困扰我的是,如何告诉按钮监听器/控制器什么是正确的事情?

1 个答案:

答案 0 :(得分:3)

使用Action“将功能和状态与组件分开。”让模型导出合适的DepositActionWithdrawAction。让控制器将每个动作与正确的 Execute 按钮相关联。引用了一些相关示例here