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!
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?EventListenerListis another way to implement the observer pattern. Such a list is common to everyJComponent, and it is appropriate when more than one event type must be managed.JFreeChartis another popular example that uses diverse events to update chart subcomponents when the data model is changed.