Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The correct way to "swap" a component in Java

I am trying to make it so that when a user clicks something on my GUI (it's irrelevant what), one JTable will disappear and another JComponent will replace it.

At the minute I am using the following code, where contentPanel is the JPanel I set as the JFrame's content pane:

contentPanel.remove(table);
contentPanel.add(component, BorderLayout.CENTER);
contentPanel.updateUI();

which works perfectly, but I just want to confirm that this is the correct method. I mean, I can't think of any other way to achieve it but that doesn't necessarily mean anything and if there's an better way to do it, in terms of performance or anything, I like to know about it...

like image 720
Andy Avatar asked Dec 22 '11 19:12

Andy


2 Answers

No, that is NOT the way to do it. You should never invoke updateUI(). Read the API, that method is only used when you change the LAF.

After adding/removing components you should do:

panel.add(...);
panel.revalidate();
panel.repaint(); // sometimes needed

(it's irrevelevant what), one JTable will disappear and another JComponent will replace it.

Maybe it is relevant. Usually a JTable is displayed in a JScrollPane. So maybe a better solution is to use:

scrollPane.setViewportView( anotherComponent );

then the scrollpane will do the validation for you.

like image 64
camickr Avatar answered Sep 23 '22 13:09

camickr


A better way is to use a CardLayout, and add both tables, then just display the correct card/table.

like image 27
Kylar Avatar answered Sep 20 '22 13:09

Kylar