I have a program where I have a JFrame
with a JButton
in it. When the user clicks the JButton
, all Components
of the
you have to force a repaint() in the frame so the frame have to repaint itself.
For me, this was a bit of an oddity. As it turned out, invoking remove(Component comp), adding the new JPanel
, and then invoking pack() worked for me.
public class Demo{
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
createAndShowGUI();
}
});
}
private static void createAndShowGUI(){
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel();
final JButton button = new JButton("Press Me");
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
frame.remove(panel);
final JPanel redPanel = new JPanel(){
@Override
public Dimension getPreferredSize(){
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g){
Graphics g2 = g.create();
g2.setColor(Color.RED);
g2.fillRect(0, 0, getWidth(), getHeight());
g2.dispose();
}
};
frame.add(redPanel);
frame.pack();
}
});
panel.add(button);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
BEFORE PRESSING THE BUTTON
AFTER PRESSING THE BUTTON
ODDITIES
For removing (and then, for example, add new JComponents) JComponents from JPanel or from top-level containers you have to call, only once and on the end of the action:
revalidate();
repaint();
And if you only resize or change JComponents:
validate();
repaint();