Sunday, July 23, 2006

Java Actions

Java Actions let you move all gui component logic to an Action object, allowing it to
be used in multiple places (i.e. appear in multiple places in the gui).
There is clearly no reason to have any more than one Action object of
each type (I believe) - so that means Actions are inherently singletons.

If that is correct, does Java treat each Action as a singleton, or
should I explicitly make them all singleton classes.

The question arises due to code like this:

JMenuItem helpItem = new JMenuItem(new HelpAction());
.....
JButton helpBtn = new JButton(new HelpAction());

I have spent a bit of time rewriting the GUI components to deal with
Actions, as they tidy the code up quite considerably.

Cheers,
Jonathan.

2 comments:

Jens said...

Regarding the actions: singletons would not work, they must be instances of the GUI class (the frame for instance). They also synchronise the enabled/disabled state, and this is different for the toolbar buttons, menu items etc in different instances of the same frame class.

You could do it like this:

class MyFrame extends JFrame {
// instance vars
Action actSave = ..;
private void initialize() {
..
actSave = new AbstractAction () {
.. // event handler must be overridden
}
this.toolbar.add(actSave);
this.filemenu.add(actSave);
}
}

Anonymous said...

A response from Scott Violet from the Java Swing team:
==================
Hi Jonathan,

That really depends upon the context and how you've designed your application. In some cases, like help, a singleton action could certainly work. I typically have singletons for each of cut, copy, paste, undo and redo.

One comment on your code. You had:

>> JButton helpBtn = new JButton(new HelpAction());
>> ..... (much later on) ....
>> new HelpAction().setEnabled(false);

To track changes to the button JButton needs to attach a listener to the Action. If you did 'new HelpAction().setEnabled(false)', unless you've done some hackery, JButton wouldn't track the change as it hasn't installed a listener on the new HelpAction.

-Scott
==================