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.