2014-02-28 26 views
0

我需要一些幫助,因爲我非常喜歡noob。在其他類中添加ActionListeners和調用方法

該程序即時嘗試在這裏,用於我的意圖工作,但當我試圖讓我的代碼更具可讀性時,我遇到了一個有關ActionListener的問題。

在我做了一個新的課程,有所有的方法之前,我用了button.addActionListener(this);,它工作得很好。現在我想把事情放在一個單獨的課堂上,我完全不知道該怎麼做。

所以我想我的問題是,我怎麼能讓ActionListener在這樣的情況下工作,還是我在這裏做的一切都是錯誤的?

這裏的,我認爲是有關我的代碼的一部分(編輯了大部分):

//Class with frame, panels, labels, buttons, etc. 

    class FemTreEnPlus { 
     FemTreEnPlus() { 
      //Components here! 

      //Then to the part where I try to add these listeners 
      cfg.addActionListener(); 
      Exit.addActionListener(); 
      New.addActionListener(); 
     } 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
     public void run(){ 
     //Start the Program in the FemTreEnPlus Class 
      new FemTreEnPlus(); 
     }  
    }); 
} 

這是與框架類,這裏的其他類,與方法

public class FemTreEnMethods extends FemTreEnPlus implements ActionListener { 

     //Perform Actions! 
    public void actionPerformed(ActionEvent ae){ 
     if(ae.getSource() == cfgButton){ 
     configureSettings(); 
     } 
     if(ae.getSource() == newButton){ 
     newProject(); 
     }  
     if(ae.getSource() == exitButton){ 
     exitProgram(); 
     } 
} 

    //All methods are down here 

在此先感謝您的幫助。

回答

3

儘管教程的示例顯示了以您所採用的方式實現的監聽器的使用,但恕我直言更適合使用匿名內部類來實現監聽器。例如:

cfgButton.addActionListener(new ActionListener() { 
    @Override 
    public void actionPerfomed(ActionEvent e) { 
     // do the stuff related to cfgButton here 
    } 
}; 

newButton.addActionListener(new ActionListener() { 
    @Override 
    public void actionPerfomed(ActionEvent e) { 
     // do the stuff related to newButton here 
    } 
}; 

exitButton.addActionListener(new ActionListener() { 
    @Override 
    public void actionPerfomed(ActionEvent e) { 
     // do the stuff related to exitButton here 
    } 
}; 

這種方法具有以下優點:

  • 監聽器邏輯被很好地分離。
  • 您不需要嵌套if塊來詢問誰是事件的來源。
  • 如果添加新按鈕,則不必修改偵聽器。只需添加一個新的。

當然這取決於案件。如果行爲對於一組組件(例如單選按鈕或複選框)的行爲將是相同的,那麼有意義的是隻有一個監聽器並使用EventObject.getSource()來處理事件的來源。建議使用此方法here並例示here。需要注意的例子還利用匿名內部類的這樣:

ActionListener actionListener = new ActionListener() { 
    @Override 
    public void actionPerformed(ActionEvent e) { 
     // do something here 
    } 
}; 
+1

+1的匿名內部類 – mKorbel

+1

雖然這個答案是這種情況下完全足夠了,我也想嘗試用行動。在這裏你有一個很好的介紹:http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html它會讓你的解決方案更加靈活 - 你可以爲許多UI組件使用一個動作並控制它的「啓用」狀態在一個地方;) –

+0

非常感謝!在這裏和那裏發生了一些錯誤之後,我最終按照你在解釋器中的方式工作(我不知道實際是什麼)。 – user2900511

相關問題