2015-04-03 79 views
-1

所以我只是在使用MVC編寫我的程序時偶然發現了這個問題。 我有一個私人JButtonView類。我編寫了將偵聽器添加到所有按鈕的方法。但是,當我試圖編碼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

回答

1

由於viewButton有私人訪問LearningVew,它將無法訪問該類上下文。

現在,在更改訪問級別之前,您可能會考慮更改您的方法。

而不是每個按鈕通知外部源添加一個ActionListener,它可能會更簡單的讓視圖監視按鈕本身。

在您就如何打破MVC之前起牀之前,這個想法會讓視圖提出一個更簡單,更專用的按鈕問題的事件,例如,viewButton可能會引起viewWasActivated什麼的,然後控制器將對此作出響應。

這需要您爲視圖和控制器定義一個interface合同,以便他們知道他們能夠傳遞給對方的信息以及可能觸發的事件。這保護了視圖控件,並且意味着您不需要不必要地公開。

更詳細地說明here

另一種選擇是使用按鈕的actionCommand屬性,而不是將按鈕的引用與事件源進行比較,但首先需要檢查動作事件的源是否是按鈕......並且我個人不喜歡「散裝」ActionListener s,他們真的很快得到凌亂...

+0

太棒了。非常感謝那個答案。我認爲可以肯定的是,JavaFX會更適合使用MVC模式的程序,而不會遇到描述問題? – Lotix 2015-04-03 22:27:03

+0

我對JavaJX並不熟悉,但是如果我記得,您仍然將「屬性」偵聽器直接附加到控件,所以您仍然會遇到類似的問題 – MadProgrammer 2015-04-03 22:34:10