Andy
Andy

Reputation: 3682

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...

Upvotes: 13

Views: 13757

Answers (2)

Kylar
Kylar

Reputation: 9334

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

Upvotes: 8

camickr
camickr

Reputation: 324128

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.

Upvotes: 19

Related Questions