I have a very simple Bank Account going on, that I built to practice my MVC knowledge. However I've hit a snag.
Since the Deposit and Withdraw screens are essentially the same, I abstracted almost all of it to a BaseWindow class.
This is the BaseWindow class:
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;
}
}
The Problem
Since I'm using the Model-View-Controller pattern, the function of the Execute button is determined in the Controller class, which is consists of the following:
...
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??
}
};
}
...
The problem is, I can't think of what goes in the createExecuteButtonListener
because I can't simply say model.deposit()
or model.withdraw()
because I don't know which window the Execute button was clicked inside of.
As far as I know, I can't use Polymorphism here because the listener is not being bound inside the DepositWindow
or WithdrawWindow
subclasses and I don't want to call them there since that would violate Model-View-Controller.
So what's bothering me is, how do I tell the button listener/controller what is the right thing to do?