Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to clear out and refill a JFrame?

843807Apr 9 2010 — edited Apr 9 2010
Hi, well could anyone tell how can I clear out and refill a JFrame with the same intial components? I want to return the JFrame to its initial state, but it just shrinks like if there wasn't any component, though I've call the method that fills it, here is the code to reproduce it.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FrameFill extends JFrame{
    static int count = 0;
    JPanel jpanel;

    public FrameFill(){
        loadComponents();
        pack();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
    }

    public void loadComponents(){
        jpanel = new JPanel();
        jpanel.setLayout(new BoxLayout(jpanel, BoxLayout.Y_AXIS));
        JButton button = new JButton("Add label");
        button.setAlignmentX(Box.CENTER_ALIGNMENT);
        button.setPreferredSize(new Dimension(200, 50));
        button.setMinimumSize(new Dimension(200, 50));
        button.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                count++;
                Component component = (Component) e.getSource();
                FrameFill f = (FrameFill) SwingUtilities.getRoot(component);
                if(count == 4){
                    f.removeAll();
                    f.loadComponents();
                    f.pack();
                    f.repaint();
                    count = 1;
                }else{
                    if(count == 1){
                        for(int i=0; i<3; i++) loadLabel(f);
                    }else if(count <=3){
                        loadLabel(f);
                    }
                }
            }
        });
        jpanel.add(button);
        add(jpanel);
    }

    public void loadLabel(FrameFill f){
        JLabel label = new JLabel("Label "+count);
        jpanel.add(label);
        jpanel.revalidate();
        f.pack();
    }

    public static void createAndShowGUI(){
        FrameFill frame = new FrameFill();
        frame.setVisible(true);
    }

    public static void main(String args[]){
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
Thanks.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 7 2010
Added on Apr 9 2010
2 comments
3,663 views