Macks
Macks

Reputation: 1776

Java Swing and the Observer Pattern

I'm looking for a way to cleanly organize my UI code in Swing.

Let's say my UI-code is structured in the following way:

class MainWindow extends JFrame {
    // SomePanel panel is added here
}
class SomePanel extends JPanel {
    // buttons, checkboxes and so on are added here
}

Lets say I'm instantiating a MainWindow-object inside my main method:

MainWindow frame = new MainWindow("I am an App");

What is the best practice for listening to ActionEvents of buttons (which are declared inside SomePanel, which is declared inside MainWindow) from within my main-method?

Thank you very much for your help!

Upvotes: 3

Views: 4404

Answers (1)

trashgod
trashgod

Reputation: 205885

Use a PropertyChangeEvent, seen here and here, to communicate results from one container to another. Other ways to implement the observer pattern are mentioned here.

Addendum: You're suggesting writing custom ActionEvents?

EventListenerList is another way to implement the observer pattern. Such a list is common to every JComponent, and it is appropriate when more than one event type must be managed. JFreeChart is another popular example that uses diverse events to update chart subcomponents when the data model is changed.

Upvotes: 5

Related Questions