It's not a secret anymore!*
The moose likes Swing / AWT / SWT and the fly likes How to tidy up a swing listener program? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "How to tidy up a swing listener program?" Watch "How to tidy up a swing listener program?" New topic
Author

How to tidy up a swing listener program?

Timmy Ryan
Ranch Hand

Joined: Dec 09, 2007
Posts: 63

I have a Swing application that has a menu, main JPanel and another JPanel to the right.
The JPanel to the right can be toggled visible or hidden by a menu option.
The menu listener is in a separate class to the menu one.

I create the menu plus the two JPanels in a JFrame class.
What I have at the moment is when I create the MenuBar I pass the rightJPanel reference to it.
Then when I create the menu listener which implements ActionListener I have to pass the rightJPanel to it as well.
In order to be able to set the rightJPanel visible or not.

How do I tidy this up?

Should I have the menu listener class a private class within the body of the menu class?
I kind of want to keep it separate though if at all possible.
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3605
    
  14

I usually make one class for each form, which contains all the listeners as well. Here's how I would recommend you do it:
Timmy Ryan
Ranch Hand

Joined: Dec 09, 2007
Posts: 63

Thanks for the response.

After thinking about it I could just have a public static method in the class that creates the rightPanel to toggle it on or off and call this from the menu listener class.
Which is basically what you have done there.
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3605
    
  14

Try to eliminate static members. Globally available operations or data make your classes easier targets for malicious code. Static fields should be reserved for constants, static methods should be utility operations.

Make one instance responsible for maintaining the panels. You should request that instance to hide or display the panels. In my case, an instance of the MyForm class is responsible for the panels.

If you want your listeners in separate classes, you only have to pass them the MyForm instance, and the listeners can call the necessary methods on the instance.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to tidy up a swing listener program?
 
Similar Threads
swing beginner - getting a jpanel launched by clicking a button
Ugh...so confused.
Question about GUI (with NetBeans IDE)
CardLayout
Class Communications