【问题标题】:Adding ActionListeners and calling methods in other classes在其他类中添加 ActionListener 和调用方法
【发布时间】:2014-04-01 09:09:14
【问题描述】:

我需要一些帮助,因为我是个菜鸟。

我试图在这里制作的程序曾经为我的意图工作,但当我试图让我的代码更具可读性时,我遇到了一个关于 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

提前感谢您的帮助。

【问题讨论】:

    标签: java swing actionlistener


    【解决方案1】:

    尽管教程的示例显示了以您的方式实现的侦听器的使用,但恕我直言,使用匿名内部类来实现侦听器更有用。例如:

    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
        }
    };
    

    【讨论】:

    • 虽然这个答案对于这种情况来说是完全足够的,但我也会尝试采取行动。在这里您有一个很好的介绍:docs.oracle.com/javase/tutorial/uiswing/misc/action.html 它将使您的解决方案更加灵活 - 您可以对许多 UI 组件使用一个操作并在一个地方控制其“启用”状态;)
    • 非常感谢!在到处弄乱了一些错误之后,我终于让它按照你解释的方式工作,在一个构造函数中(我也不知道它到底是什么)。
    • @guitar_freak 这是个好建议。我从来没有想过使用动作,因为我习惯于使用匿名动作监听器,但下次也许我会尝试一下。
    猜你喜欢
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    相关资源
    最近更新 更多