简体   繁体   中英

Rearranging JPanels within a JFrame's content pane?

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();

I suspect that your use of a stack is the problem. Try changing it to a list instead.

   List<Component> panels = new ArrayList<Component>();
   for(Component c : this.getContentPane().getComponents())
        panels.add(c); 

   this.getContentPane().removeAll();    
   Collections.shuffle(panels);   

   this.getContentPane().setLayout(new GridLayout(3,3));

   for(Component c: panels){
       this.getContentPane().add(c);
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM