I have created a JFrame subclass containing 9 JPanels using a GridLayout (3x3). I'm trying to design a method that randomly rearranges the JPanels within the JFrame. Here's what I have so far:
public void shuffle() {
Stack<Component> panels = new Stack<Component>();
for(Component c : this.getContentPane().getComponents())
panels.push(c);
this.getContentPane().removeAll();
Collections.shuffle(panels);
while(!panels.isEmpty())
this.getContentPane().add(panels.pop());
this.repaint();
}
After this method is run, the JPanels are in the exact same positions in the GridLayout as they were before! I've confirmed that the JFrame is indeed getting repainted, that my stack is getting shuffled, and that the removeAll() and add() methods are working. The content pane seems to be remembering where the JPanels were, so re-ordering the add() calls doesn't seem to work.
Where am I making a mistake? Does anyone know of a better way to shuffle the positions of JPanels within a layout? Thanks in advance!
Perhaps your problem is that you need to call revalidate on the container after adding components to it. This tells the layout managers to do their thing -- to layout the components they contain.
((JPanel)getContentPane()).revalidate();
getContentPane().repaint();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With