Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removeAll not removing at next validate?

Tags:

java

swing

Can someone explain why the following doesn't work as I expect?

Pressing the button 'should' result in the display only containing the (empty) JScrollPane, ie the input field and button should disappear. However they stay until the component is resized...

public static void main(String[] args)
{
    JFrame frame = new JFrame("test");
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    final JPanel panel = new JPanel();

    Container cp = frame.getContentPane();
    cp.setLayout(new FlowLayout());
    cp.add(new JScrollPane(panel));

    Component textField = new JTextField("i am input");
    JButton button = new JButton(new AbstractAction("i am pressy")
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            // this is already on the EDT
            panel.removeAll();
            panel.revalidate();
        }
    });

    panel.setLayout(new FlowLayout());
    panel.add(textField);
    panel.add(button);

    frame.pack();
    frame.setVisible(true);
}

Thanks for your help. p.

like image 693
pstanton Avatar asked Apr 27 '11 23:04

pstanton


1 Answers

When updating a visible GUI the code should be:

panel.revalidate();
panel.repaint(); // sometimes needed, this appears to be one of them
like image 108
camickr Avatar answered Sep 30 '22 18:09

camickr