所以我只是在使用MVC編寫我的程序時偶然發現了這個問題。 我有一個私人JButton
在View
類。我編寫了將偵聽器添加到所有按鈕的方法。但是,當我試圖編碼ActionPerformed()
部分時,會拋出一個關於JButton
不可見的錯誤。處理MVC模型,jbuttons和ActionListener的getSource()方法
給公衆設置JButton
完全解決問題,但這是正確的做法嗎?是否有另一種方法來設定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
}
}
}
}
視圖和控制器類(無模型)的快速響應用於便捷。 http://www.hastebin.com/ecawolusal.avrasm
太棒了。非常感謝那個答案。我認爲可以肯定的是,JavaFX會更適合使用MVC模式的程序,而不會遇到描述問題? – Lotix 2015-04-03 22:27:03
我對JavaJX並不熟悉,但是如果我記得,您仍然將「屬性」偵聽器直接附加到控件,所以您仍然會遇到類似的問題 – MadProgrammer 2015-04-03 22:34:10