GUI中监听器的嵌套类的优点 [英] Advantages to Nested Classes For Listeners in GUIs

查看:220
本文介绍了GUI中监听器的嵌套类的优点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于体积适中的项目,我被告知当你有扩展JPanels的类时,最好的做法是使用嵌套类来实现监听器。例如,我可以有一个扩展JPanel的类FactoryScreen,并有一个嵌套类FactoryScreenBrain,它实现了所有必要的监听器。

For decently sized projects I've been told that when you have classes extending JPanels that the best practice is to use nested classes to implement the listeners. For example I could have a class FactoryScreen that extends JPanel, and have a nested class FactoryScreenBrain that implements all the necessary listeners.

我从来没有能够以这种方式为我的类封装具体的好处或缺点得到一个很好的解释,直到现在总是只有扩展的类JPanel和实现监听器。有人能为我提供一些指导吗?

I've never been able to get a good explanation for specific benefits or disadvantages to encapsulating my classes in this fashion, and until now have always just had classes that both extend JPanel and implement listeners. Can someone provide me some guidance on this?

推荐答案

为听众设置内部类会使所有听众的目的非常明确。它有时也可以避免很多,如果检查的代价是更多的代码。

Having inner classes for your listeners makes the purpose of all those listeners very clear. It can also sometimes avoid many if checks at the expense of a bit more coding.

如果你有一个小组

public class MyPanel extends JPanel implements ActionListener
...
    button1.addActionListener(this);
    button2.addActionListener(this);
    checkbox1.addActionListener(this);
    timer3.addActionListener(this);

    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource() == button1)
        else...
        ... //potentially many elses
    }

很难确切知道发生了什么你的actionPerformed,因为它一次处理这么多不同的事件。有一个小组:

it's very difficult to see exactly what is going on in your actionPerformed because it handles so many different events at once. Having a panel:

public class MyPanel extends JPanel
...
    button1.addActionListener(new ButtonListener());
    button2.addActionListener(new ButtonListener());
    checkbox1.addActionListener(new CheckBoxListener());
    timer3.addActionListener(new TimerListener());

    private class TimerListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            //do stuff related only to timers
        }
    }

现在,如果您的计时器出现问题,您可以轻松识别问题。

Now if your timer has an issue you can easily identify the class with the problem.

更重要的是,在大规模上,它使您的代码更具可读性。如果其他人想要在这个类上工作并且他们需要使用计时器修复事件处理,他们不必搜索你的ifs以找到具有计时器逻辑的部分。

Even more importantly, on the grand scale, it makes your code more readable. If somebody else wants to work on this class and they need to fix event handling with the timer, they don't have to search through your ifs to find the part with the timer logic.

这篇关于GUI中监听器的嵌套类的优点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆