Reputation: 25
In my view I have created a new JButton named jbOk. I have done jbOk.setActionCommand("OK"). In my controller I implement ActionListener and override the actionPerformed() method. Inside the actionPerformed() method I made an If statement and set it equal to the value that I set to the JButton. If it is equal, it it must print something. But it doesn't. Even outside the if statement I made a print statement and it doesn't print.
I know the JButton doesn't have an actionListener. My question is how do I add an actionListener to the JButton that is in the view, so that it can use the actionPerformed() method that is in the controller? I'd like to keep the ActionListener in the controller.
My actionPerformed method in my controller:
@Override
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if(action.equals("OK")) {
System.out.println("WillThisPrint?");
}
System.out.println("WillThisPrint2?");
}
My constructor in my view:
public MapView(){
super(new FlowLayout());
setSize(900, 450);
this.add(getRouteComboBox());
jbOk = new JButton("OK");
jbOk.setActionCommand("OK");
add(jbOk);
} //constructor end
Upvotes: 0
Views: 693
Reputation: 19565
Well, you can keep implementation of the ActionListener
in the controller but you need to add the instance of the controller inside the view:
public MapView(){
super(new FlowLayout());
setSize(900, 450);
this.add(getRouteComboBox());
jbOk = new JButton("OK");
jbOk.setActionCommand("OK");
add(jbOk);
//
jbOk.addActionListener(new MyController());
}
So, you just need to decide how you create the instance of the controller and how you pass it into the view:
// MapView class
// using field
private MyController controller = new MyController();
//...
jbOk.addActionListener(controller);
MapView
constructor:private MyController controller;
public MapView(MyController controller) {
this.controller = controller;
// ...
jbOk.addActionListener(this.controller);
}
jbOk.addActionListener(MyController.getInstance());
public class MyController {
private static MyController instance = new MyController();
public static MyController getInstance() {
return instance;
}
// private constructor to disable creation of MyController elsewhere
private MyController() {}
}
Upvotes: 1