簡體   English   中英

在其他類中添加ActionListener和調用方法

[英]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.

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