[英]Adding ActionListeners and calling methods in other classes
我需要幫助,因為我是菜鳥。
我試圖在這里制作的程序曾經按照我的意圖工作,但是當我試圖使代碼更具可讀性時,我遇到了有關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
在此先感謝您的幫助。
盡管本教程的示例顯示了以您的方式實現的偵聽器的使用,但是IMHO使用匿名內部類來實現偵聽器更為有用。 例如:
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()處理事件的源是有意義的。 此方法在此處建議並在 此處進行示例。 請注意,示例還以這種方式使用匿名內部類:
ActionListener actionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// do something here
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.