I created a subclass of JFrame containing 9 JPanels using GridLayout (3x3). I am trying to develop a method that randomly rearranges JPanels inside a JFrame. Here is what I still have:
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 running this method, the JPanels are in the same positions in the GridLayout as before! I confirmed that the JFrame really redraws, that my stack is shuffled, and that the methods removeAll()both add()work. The content area seems to remember where the JPanels were, so call reordering add()doesn't work.
Where am I making a mistake? Does anyone know a better way to shuffle JPanels positions in a layout? Thanks in advance!
source
share