Reputation: 1275
In my project I've got a JPanel (bottomPanel) in a JFrame that needs to be swapped so I'm using a CardLayout on bottomPanel.
In my parent JFrame I've essentially got this code in a method (setBottomPanel):
bottom.add(p.toString(),p);
bottomLayout.show(bottom, p.toString());
And I call it once in the parent JFrame's constructor and it works fine. However, I'm passing a reference to this parent JFrame to other JPanels and if I call setBottomPanel() on the reference it has no effect, the panel doesn't change.
I did have it using bottomLayout.next(bottom)
and this did change the panel, but to an empty one.
Update:
It appears it IS loading correctly, I changed the code back to calling next()
but the JPanel that is being passed is empty. Could this be because I'm using GridLayout on the JPanel that is being added to the bottomPanel? I'm not passing in the layout reference at all...
Upvotes: 0
Views: 1236
Reputation: 1275
Figured it out:
The issue was that the JPanel being passed to the method had a GridLayout, and elements were being added to the layout. Once I changed the way that the JPanel was being constructed the code then worked fine :)
Thanks!
Upvotes: 0
Reputation: 4444
Are you sure the code example you presented reflects the source code you're working with? Because, assuming that bottom
is a JPanel
and p
is a JComponent
, your call to bottom.add
should pass the component and then the layout constraint:
bottom.add (p, p.toString());
When you call setBottomPanel()
from the other JPanels, are you adding the components to bottom
again or are you only adding them if they're new? If the former, it's very likely that bottom
simply isn't being revalidated or repainted. From the Java API: "If a component has been added to a container that has been displayed, validate must be called on that container to display the new component."
Upvotes: 2