So i just stumbled upon this problem while coding my program using MVC.
I have a private JButton
in the View
class. I wrote the method to add the listener to all respective buttons. However, when i'm trying to code the ActionPerformed()
part it throws an error about JButton
not being visible.
Setting JButton
to public solves the problem completly, but is it the right thing to do? Is there another way of setting the ActionListener
without making the JButton
public?
public class learningView extends JFrame {
private JButton viewButton = new JButton("View Resources");
public void addButtonListener(ActionListener listenerForButtons) {
viewButton.addActionListener(listenerForButtons);
saveButton.addActionListener(listenerForButtons);
addButton.addActionListener(listenerForButtons);
}
}
public class learningController {
private learningModel theModel;
private learningView theView;
public learningController(learningModel theModel, learningView theView) {
this.theModel = theModel;
this.theView = theView;
this.theView.addButtonListener(new buttonListener());
}
class buttonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == theView.viewButton) {// This is where problem arises
}
}
}
}
Hastebin for view and controller classes (without model) for the convienience. http://www.hastebin.com/ecawolusal.avrasm