簡體   English   中英

當 ActionListener 位於不同的 class 時,如何訪問 ActionEvent 的源?

[英]How do I access the source of an ActionEvent when the ActionListener is located in a different class?

我無法理解這一點。 我第一次嘗試遵循 MVC 模式,但現在無法訪問 ActionEvent 的源,因為 ActionListener 位於不同的 class 中。 但是讓代碼說話......

在“視圖”中:

// ControlForms.java

...

private JPanel createSearchPanel() throws SQLException {

...

comboBoxCode = new JComboBox(); // Field comboBoxCode -> JComboBox()
    SwingUtilities.invokeLater(new Runnable() {  
        public void run() {  
            AutoCompleteSupport<Object> support = AutoCompleteSupport.install(
comboBoxCode, GlazedLists.eventListOf(jnlCodeArray));
        }  
    });  // Auto-Complete comboBox from GlazedLists

...

public void setComboListener(ComboListener comboListener) {
    comboBoxCode.addActionListener(comboListener);
}

...

}

然后,在我所說的 controller 中,我有兩個不同的類:

// Controller.java

    public MyController() throws SQLException {
...
    addListeners();
}

...

    private void addListeners(){
    View view = getView();
    getView().getControlForm().setComboListener(new ComboListener());

}

public class ComboListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
    System.out.println("ComboBox listened to! e = " + e.toString());
}
}

現在, e顯然沒有給出變量的名稱(目前我希望它會),所以我if測試e.getSource()

因此,我的問題是:是否一種方法可以查詢(例如,通過if )e 的來源,或者b)一種不太復雜的方法來獲取變量名?

非常非常感謝您的見解和提示!

為什么需要變量名? 為什么不能像這樣進行事件處理

public class ComboListener implements ActionListener 
{
    public void actionPerformed(ActionEvent e) 
    {
        JComboBox source = (JComboBox)e.getSource();

        //do processing here
    }
}

我認為,如果您需要根據變量名進行處理,顯然您需要針對不同的組合框使用不同的偵聽器。

通常,只有兩種情況應該使用這樣的偵聽器:a)您將以相同的方式處理一組對象的某個事件,或者 b)您只將偵聽器用於一個 object。 在后一種情況下,無論如何我寧願在本地處理事件。

也就是說,對您的問題的直接回答是:您不必檢查ActionListener實現內部以查看適當的 object 是否是事件的來源; 您應該只將ActionListener添加到那個 object。

最后一點:在不知道您的架構細節的情況下......通常,MVC 會將所有事件處理視為視圖的一部分(它減少了耦合),並且視圖將傳遞命令或方法調用或您自己的事件(即,不是 Swing 的) 到 Controller。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM