Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to tidy up a swing listener program?

 
Timmy Ryan
Ranch Hand
Posts: 63
IntelliJ IDE Java Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 5790
61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 63
IntelliJ IDE Java Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 5790
61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic