2011-04-21 39 views
1

我目前正在開發一個桌面應用程序。我有菜單欄,其中帶有ALT-R助記符的RUN命令。此外,我有一個運行按鈕在其中一個框架&我已經宣佈一個ActionListener相同。有沒有辦法使用相同的ActionListener作爲運行命令menu-item ..?還是應該再次重申聲明..?如何在不同的類中使用動作偵聽器?

+0

這些類是孤立的。此外,班級中使用的本地/私有變量會發生什麼? – 2011-04-21 12:33:22

回答

0

如果您從第一堂課開始第二堂課,那麼您可以將您實施ActionListener的班級轉到第二堂課。即

class A implements ActionListener{ 
    @Override 
    public void actionPerformed(ActionEvent ae) { 
    //--- coding......... 
    } 

    //--- Somewhere in this class 
    B b=new B(this); 
} 

class B{ 
    A a; 
    public B(A a){ 
     this.a = a; 
    } 
    //-- now use this.a where you wanna set actionListener 
} 

或者你也可以很容易地把它作爲:

class B{ 
    //-- Where you want to add ActionListener 
    button.addActionListener(new A()); 
} 
+0

i thnk dis是如何做到這一點的。我們不得不重新聲明局部變量,全局都是類的......感謝支持..! – 2011-04-21 13:02:35

0
class ActionL implements ActionListener{ 
    // Here to override 
    public void actionhapp(ActionEvent ae) { 
    // do your code 
    } 


    BAction b=new BAction(this); 
} 

class BAction{ 
    ActionL a; 
    public BAction(A a){ 
     this.a = a; 
    } 


} 

這裏是辦法u能做到

+2

如果您複製我的答案,但至少更改名稱正確.....不擔心; ;-) – 2011-04-21 12:40:38

2

考慮存儲在靜態地圖中的所有聽衆。他們的邏輯必須是獨立於任何「外部類」,可以肯定的,因爲他們必須在任何情況下運行:

public static Map<String, ActionListener> listeners = new HashMap<String, ActionListener>(); 
static { 
    listener.put("RUN", new ActionListener() { 
    // implementation of the "Run" actionlistener 
    }); 
    // more listeners 
} 

,稍後:

something.addActionListener(SomeManager.listeners.get("RUN")); 
0

其實另一種選擇是使用ActionLister並在包含按鈕和其他對象的類上進行設置,或者甚至使用每個UI小部件的ActionListener,然後僅向包含該邏輯的類發出調用。就責任而言,這對我來說似乎有點乾淨。

JButton myButton = new JButton("RUN"); 
myButton.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent ae) { 
     myLogicClass.executeRun(); 
    } 
}; 

public class MyLogicClass { 
    public void executeRun() { //or parms if you need it. 
     //do something in here for what you want to happen with your action listener. 
    } 
} 

這讓我感覺更乾淨,因爲它試圖將UI和邏輯保持在不同的類中。但它也取決於你想做什麼「做某事」。

相關問題