Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swing: How JDialogs talk back to the JFrame

I'm building my first Swing app and am trying to figure out how my JDialogs - exclusively invoked when the user selects a JMenuItem - can update the components in the main client area of the JFrame which is the parent "window" of the whole app.

This is the design I've come up with, but don't know if its: (1) just plain bad, (2) not the standard (thus best) way, or (3) if I'm totally off-base here. Any suggestions are enormously appreciated.

Basically, the user selects a JMenuItem, which launches a JDialog. The user interacts with the components on the dialog, and then clicks "Done". If everything validates, the JDialog closes, and I want the parent window (a JFrame) to have its state updated (and eventually rippled out into its components).

My design:

Have an AppStateController that is a member of the JFrame subclass (my application). I would then create an AppStateChangeListener and AppStateChange EventObject subclass so that whenever a dialog validates and closes, it fires an AppStateChange event. Since the parent JFrame is the only registered listener to that event, I could define a handler that gets the event passed to it. I would make sure the AppStateChangeEvent had enough metadata to describe all the possible changes.

In theory, I like this approach: it should be clean and free of "spaghetti"-type calls to multiple controls every time a different event fires. However, I fear it may be overkill.

What do best practices dictate here? I'm not really a GUI person!

like image 203
IAmYourFaja Avatar asked Aug 16 '11 18:08

IAmYourFaja


1 Answers

Java has several ways to implement the observer pattern; several are discussed here.

The mechanism prescribed by EventListenerList is probably the most general, as it would allow you to define your own event and listener types, and it is familiar to Swing programmers. Instead of making the JFrame a listener, let the highest level JComponent do so. Each instance of JComponent has a suitable protected member, listenerList.

Bound Properties are also an excellent choice, as shown here.

If you go with Observable, you'll need to use a delegate.

Addendum: As concrete examples, jfreechart uses the EventListenerList scheme to manage chart, dataset and series events. In contrast, jcalendar uses bean properties to notify listeners of widget selections.

like image 170
trashgod Avatar answered Oct 18 '22 04:10

trashgod