我需要一些幫助,因爲我非常喜歡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
在此先感謝您的幫助。
+1的匿名內部類 – mKorbel
雖然這個答案是這種情況下完全足夠了,我也想嘗試用行動。在這裏你有一個很好的介紹:http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html它會讓你的解決方案更加靈活 - 你可以爲許多UI組件使用一個動作並控制它的「啓用」狀態在一個地方;) –
非常感謝!在這裏和那裏發生了一些錯誤之後,我最終按照你在解釋器中的方式工作(我不知道實際是什麼)。 – user2900511