“交换”的正确方法Java中的一个组件 [英] The correct way to "swap" a component in Java
问题描述
我试图这样做,以便当用户点击我的GUI上的内容(这与什么无关)时,一个 JTable
将消失,另一个 JComponent
将替换它。
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.
当我使用以下代码时,其中 contentPanel
是 JPanel
我设置为 JFrame
的内容窗格:
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...
推荐答案
不,这不是办法。你永远不应该调用updateUI()。阅读API,该方法仅在您更改LAF时使用。
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
(这是无关紧要的),一个JTable会消失另一个JComponent将替换它。
(it's irrevelevant what), one JTable will disappear and another JComponent will replace it.
可能它是相关的。通常,JTable显示在JScrollPane中。所以也许更好的解决方案是使用:
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.
这篇关于“交换”的正确方法Java中的一个组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!