Search code examples
javaswingawtlayout-managercardlayout

Lazy initialization - test if CardLayout has a specific panel added to it


I have a list box with a list of strings. Based on the string selected I need to display a group of text boxes below. My approach is to create a JPanel for each set of text boxes and then put all these JPanels into a card layout. When the user selects a particlar string, I will flip the card layout to display the appropriate panel with the text boxes. However, I dont want to create all the panels before hand, because there is a chance that the user may not ever select a few list values. Hence only when the user selects a list value, I want to check if the card layout has this card (or panel) added to it and if not, then create the new panel (with text boxes) and add it to the card layout.

But I dont see any API in the CardLayout class which lets me test if a particular panel has been added to the card Layout. There is only

void addLayoutComponent(String name,Component comp)

and this doesnt return anything to test successful adding of the panel to the card laout.

How can I do this?


Solution

  • There is a Hashtable (not even HashMap) used by the CardLayoutlayout manager but this is only used internally and not exposed externally.

    Here are 2 possible solutions:

    1. You could keep a separate HashMap<String, JPanel> to account for the panels you have created.
    2. You could keep a JPanel reference list and check & instantiate if null before adding to the receiving container.