This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I have a Main JPanel with a JSplitPane and on the two parts of the split pane are two more panels, panel A and panel B. The panel on one side (eg. A )contain some buttons. Each button calls a panel or form that must be shown on panel B. When another button is pressed, the form should disappear and the panel to which the second button is for, should be displayed.
Do I have to create an instance of panel B in panel A so that the buttons can control whats in panel B? Also, is there a better way than using setVisible, like a way which I can create the instance when needed and remove it when another panel is being loaded or created?
You add a main panel to the split pane (lets call this cardPanel), and give it an instance of CardLayout (call it cardLayout). You add every panel (or other component) you need to show in the card panel with a unique identifier, and you show one using cardLayout.show(cardPanel, identifier). The only thing the buttons need to know is the identifier of the panel, plus references to the card panel and layout.
Originally posted by Darrell Morello: So this means I dont have to create and destroy panels? Will it take up much memory? And can I control the cardlayout panel even though I have the buttons on another panel?
Yes, no, yes.
Moving to Swing/AWT...
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Originally posted by Darrell Morello: So this means I dont have to create and destroy panels?
You need to create each panel once, then you can use that one instance.
Will it take up much memory?
Well, it has one instance of all panels active all the time. So it is more memory consuming than having only the instance you display in memory. However, since you know nothing about garbage collection except that you know nothing, you might still have all panels in memory even though you have only one reference. So basically, the amount of memory this solution needs may be higher than having only one reference, but it might not. Furthermore, if you only create panels once and then hide them, there is no difference in memory.
And can I control the cardlayout panel even though I have the buttons on another panel?
As long as those buttons / their action(listener)s have a reference to both the panel and the layout.