Friday, May 6, 2011

How do I switch panels inside a frame depending on a button action?

I have created an application that has a toolbar, menubar and content area. I have added the menu and toolbar to the application window, but I am stuck with displaying the panel in content area based on the button action (like add, display) which is clicked through the toolbar. Is this a right way to do this? Is there any better way to do this?

From stackoverflow
  • If I understand correctly, you want to have multiple JPanels, only one of which is shown at a time? If that's the case, it sounds like a CardLayout is what you need. You basically add all your JPanels to it with unique names, and then you can tell the CardLayout which of them to show.

    : thank you, this sounds like good idea and I will give it a try. I never thought of this, i was trying assign a Jpanal variable to a content area pane and then change the value of Jpanel variable on the basis of button pressed.
  • I think CardLayout is probably what you want, but if something like memory usage is a concern and you really want to remove and add a new JPanel/Component, you need to remove the old JPanel and add the new one (with proper constraints and/or index depending on the layout). You'll have to validate() the content pane after you make the switch.

0 comments:

Post a Comment