This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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.
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.
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.