SomeShinyObject
SomeShinyObject

Reputation: 7801

Java Individual ActionListeners and an Overarching ActionListener

Perhaps I am going about this the wrong way. Let me know Using Swing and AWT, I have several buttons set up on a frame and they each have an ActionListener corresponding to their specific function I.E.

JButton foo_button = new JButton("Foo-Me");
foo_button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        //Fancy schmancy code work
    } 
})
JButton bar_button = new JButton("Bar None");
bar_button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        //Fancy schmancy code work
    } 
})

So each of these buttons do their own thing. However, what if I want all the buttons to do a certain thing (the same exact method for each), in my case, clear a label, before they do their own thing.

Obviously I could add whatever_label.setText("") to each actionPerformed() but that entails a lot of duplication, something I'm not so much a fan of.

Oh Java and Swing gurus come to my aid.

Upvotes: 1

Views: 223

Answers (3)

Catalina Island
Catalina Island

Reputation: 7126

I think the best way to do this is to use Action. That way all the listeners always do the same thing.

Upvotes: 3

Robin
Robin

Reputation: 36601

Another possibility is to use the 'Decorater' pattern, and write an ActionListener decorator for the common behavior. Your code would then be of the form

bar_button.addActionListener(new MyActionListenerDecorator( new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        //Fancy schmancy code work
    }  }) );

Upvotes: 3

MByD
MByD

Reputation: 137282

You can subclass your own implementation of ActionListener:

private static abstract class MyListener implements ActionListener {

    @Override
    final public void actionPerformed(ActionEvent evt) {
        theSameTask();
        uniqueTask(evt);
    } 
    private void theSameTask() {
        // the identical task
    }
    public abstract void uniqueTask(ActionEvent evt);
}

And then, the new listeners will look like this:

JButton bar_button = new JButton("Bar None");
bar_button.addActionListener(new MyListener() {
    @Override public void uniqueTask(ActionEvent evt) {
        //Fancy schmancy code work
    } 
});

Upvotes: 7

Related Questions