Swing: how JDialogs talk to JFrame

I am building my first Swing application and trying to figure out how my JDialogs β€” exclusively called when a user selects JMenuItem β€” can update components in the main JFrame client area, which is the parent window of the entire application.

This is the design that I came up with, but I don’t know if it is: (1) just a bad way, (2) not a standard (thus, better) way, or (3) if I'm completely out of base here. Any suggestions are extremely appreciated.

Basically, the user selects JMenuItem, which launches JDialog. The user interacts with the components in the dialog box, and then click Finish. If everything is checked, JDialog closes, and I want the parent window (JFrame) to update its state (and ultimately spill over into its components).

My design:

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

In theory, I like this approach: it should be clean and free of spaghetti calls to several controls every time another event is triggered. However, I am afraid that this might be redundant.

What do the best practices dictate? I am not a GUI person!

+6
source share
1 answer

There are several ways in Java to implement an observer pattern ; several are discussed here .

The mechanism prescribed by EventListenerList is probably the most general, as it allows you to define your own types of events and listeners, and he is familiar with Swing programmers. Instead of making a JFrame listener, let the highest level JComponent do this. Each JComponent instance has a matching member protected , listenerList .

Associated properties are also a great choice, as shown here .

If you switch from Observable , you will need to use a delegate.

Appendix: As specific examples, uses the EventListenerList scheme to manage diagrams, datasets, and series events. In contrast, uses bean properties to notify listeners of widget choices.

+5
source

Source: https://habr.com/ru/post/895178/


All Articles