【发布时间】:2015-06-08 23:51:35
【问题描述】:
所以我在使用 MVC 编写程序时偶然发现了这个问题。
我在View 类中有一个私人 JButton。我编写了将侦听器添加到所有相应按钮的方法。但是,当我尝试对 ActionPerformed() 部分进行编码时,它会引发关于 JButton 不可见的错误。
将JButton 设置为public 可以完全解决问题,但这样做是否正确?是否有另一种设置ActionListener 而不公开JButton 的方法?
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。 http://www.hastebin.com/ecawolusal.avrasm
【问题讨论】:
标签: java model-view-controller jbutton actionlistener private