How to program toggle-able JPanels?
April 10, 2006 12:32 PM   Subscribe

Java question: how to program a toggle-view in a GUI?

Basically, I want to have two seperate JPanels that are the same size and occupy the same space in the frame, but only allow one to be visible at any time, so that the view can be toggled in between these two panels with a radio button. Using the glass pane seems to be out because it covers the menu bar, and I've had absolutely zero luck with getting the layered pane to work out, so I'm kind of stuck. Any help would be appreciated!
posted by invitapriore to Computers & Internet (8 answers total)
Its been a while since I've done SWING programming, but as I recall it should be fairly easy.

1. Make a JPanel to hold the 2 subpanels and set its size.
2. Create the 2 sub JPanels and set their preferred sizes.
3. Write a custom LayoutManager to position the 2 sub panels on the parent panel at the correct location.
4. Call panel.setVisible(false) on the first sub panel and panel.setVisible(true) on the other
5. Code the event handler for your radio buttons to set the visibilty on the sub panels correctly

You shouldn't need any class panes or anything- just the setVisible() function and tha ability to do your own layout.
posted by gus at 12:55 PM on April 10, 2006

There is actually a container that can be used to do this, supposedly. It's like a tabbed component, but without the tabs.

/looks up API docs

A JLayeredPane might do what you want. So you would have something like:

1) you're main window/frame/whatever
1.A) your checkboxes
1.B) A JLayeredPane
1.B.a) Panel one
1.B.b) Panel two
posted by delmoi at 1:08 PM on April 10, 2006

Arg, metafilter ate my  s!
posted by delmoi at 1:09 PM on April 10, 2006

Oops, looks like you already tried a layered pane.

The next step IMO, would be to simply have two panes. When you want to show one, remove the other one (if it's there) and then add this one to another sub-pane. Continue to swap them out as needed. I've never tried anything like that, though.
posted by delmoi at 1:13 PM on April 10, 2006

Try CardLayout
posted by azlondon at 1:21 PM on April 10, 2006

You want something like the CardLayout or CardPanel.

I don't believe the JLayeredPane is intended to be used for card layouts; it's mostly for when you need greater control over the z ordering, i.e. when you have components floating over one anthoer.
posted by Loser at 1:21 PM on April 10, 2006

Ah, I was thinking of CardLayout, but I couldn't find it in swing, it's part of the old AWT.
posted by delmoi at 5:14 PM on April 10, 2006

Metafilter eats all the nbsps in the composition box as soon as you do a preview. I work around this by composing anything with nbsps in an external editor, then doing paste - preview - paste - post.
posted by flabdablet at 5:33 PM on April 10, 2006

« Older Creative works by people with OCD?   |   A simple off-line project management application? Newer »
This thread is closed to new comments.