Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 719
Macks Avatar asked Mar 13 '26 17:03

Macks


1 Answers

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.

like image 93
trashgod Avatar answered Mar 16 '26 11:03

trashgod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!