Swing component listening to itself vs inner classes

大憨熊 提交于 2019-12-11 04:46:13

问题


I just got some bad feedback on a uni project and need some impartial clarification;

Can anyone explain when I should use (anonymous) inner listener classes vs components that listen to themselves? (a vs b)

a)

public class myButton extends JButton {

    public myButton() {

        addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                // handling code...

            }
        });
    }
}

b)

public class myButton extends JButton implements ActionListener {

    public myButton() {

        addActionListener(this);
    }

    public void actionPerformed(ActionEvent e) {

        // handle the event
    }
}

Thanks guys, Mitch


回答1:


c)

JButton myButton = new JButton(); 
myButton.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
        // handling code...
    }
}); 



回答2:


For cases where you have multiple buttons with different behavior it is more convenient to assign a separate anonymous class for each button, you can still implement ActionListener in your class and handle the event according to the source:

void actionPerformed(ActionEvent e) { 
    if (e.getSrouce() == button1)
    { ... }
    else if (e.getSource() == button2)
    { ... }
    // ...
} 



回答3:


I think it may be a personal preference. Anyway I would always go for inner classes as a way to separate responsabilities and organizing the code.

In particular, they are the only way to use the Adapter classes (empty classes that already implement some particular Listener interfaces, so you only need to overwrite the methods you need and you do not need to provide an empty implementation of those that you do not need).




回答4:


The point is that when you declare your myButton class to implement ActionListener, you increase its visible API (ie add a new public actionPerformed() method, freely callable by any code that holds a reference to a myButton).

Since you probably don't want "actionPerformed" to be part of myButton API, you ought to use an inner class, that will preserve the public API of myButton.

Note that Swing classes are full of bad examples like that where the public methods are explicitly commented as "implementation detail, do not call directly", very bad design decision actually.



来源:https://stackoverflow.com/questions/5856083/swing-component-listening-to-itself-vs-inner-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!