Reputation: 961
I tried
frame.removell();
frame.revalidate();
frame.repaint();
It didn't worked. Then I tried
frame.getContentPane().removeAll();
frame.revalidate();
frame.repaint();
But this isn't working also. I am simply trying to remove all the components from existing frame and reload the same frame with Same components with different values but with the above codes, application is simply showing duplicate panels in my existing frame.
Upvotes: 0
Views: 2248
Reputation: 18812
You need to validate() after you remove. Here is a working demo of remove all and adding a new component :
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.event.MouseInputAdapter;
public class Test extends JFrame {
private int click_count = 0;
public Test(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout());
addLabel();
validate();
pack();
}
/**
*
*/
private void labelClicked() {
getContentPane().removeAll();
addLabel();
revalidate();
repaint();
click_count++;
}
/**
*
*/
private void addLabel() {
JLabel label = new JLabel("click count " + click_count);
label.setPreferredSize(new Dimension(200,100));
label.addMouseListener(new MouseInputAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
labelClicked();
}
});
add(label);
}
public static void main(String[]arghs){
Test frame = new Test();
frame.setVisible(true);
}
}
Alternatively you could change a component's properties by updating it, without removing it and adding a new one:
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.event.MouseInputAdapter;
public class Test extends JFrame {
private JLabel label;
private int click_count = 0;
public Test(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel("click count " + click_count);
label.setPreferredSize(new Dimension(200,100));
label.addMouseListener(new MouseInputAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
labelClicked();
}
});
add(label);
validate();
pack();
}
/**
*
*/
private void labelClicked() {
click_count++;
updateLabel();
repaint();
}
/**
*
*/
private void updateLabel() {
label.setText("click count " + click_count);
}
public static void main(String[]arghs){
Test frame = new Test();
frame.setVisible(true);
}
}
Upvotes: 3