Swing组件可以添加到多个容器中吗?

发布于 2024-10-10 10:07:39 字数 143 浏览 0 评论 0原文

我正在尝试(测试其他内容)将一个 JButton 引用添加到两个 JPanels 中来测试它,它从添加到的第一个面板中消失!

那么,一个Swing组件就不能添加到多个容器中吗?

先感谢您。

I'm trying (testing something else) to add one JButton reference into two JPanels to test it, and it disappears from the first panel it was added to!

So, can't a Swing component be added to multiple containers?

Thank you in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

暖风昔人 2024-10-17 10:07:39

来自: http://download.oracle.com/javase/tutorial/uiswing /components/toplevel.html

每个 GUI 组件都可以包含
只有一次。如果一个组件已经
在一个容器中,你尝试添加它
到另一个容器,组件
将从第一个中删除
容器,然后添加到
第二。

From: http://download.oracle.com/javase/tutorial/uiswing/components/toplevel.html:

Each GUI component can be contained
only once. If a component is already
in a container and you try to add it
to another container, the component
will be removed from the first
container and then added to the
second.

世界如花海般美丽 2024-10-17 10:07:39

正如您所发现的,您无法共享组件。不过,您还可以使用其他方法。

对于 JButton,您可以共享一个 Action:

JButton button1 = new JButton( someAction );
JButton button2 = new JButton( someAction );

阅读 Swing 教程中 如何使用操作了解更多信息。

在其他情况下,您可能希望共享模型:

DefaultTableModel model = new DefaultTableModel( ... );
JTable table1 = new JTable( model );
JTable table2 = new JTable( model );

解决方案取决于您的要求。

As you've discovered, you can't share components. However there are other approaches you can use.

In the case of a JButtons you can share an Action:

JButton button1 = new JButton( someAction );
JButton button2 = new JButton( someAction );

Read the section from the Swing tutorial on How to Use Actions for more information.

In other cases you might want to share the model:

DefaultTableModel model = new DefaultTableModel( ... );
JTable table1 = new JTable( model );
JTable table2 = new JTable( model );

The solution depends on your requirement.

念三年u 2024-10-17 10:07:39

解决了。

检查 Java 教程的 UI-Swing 部分,它说。

每个 GUI 组件只能包含一次。如果一个组件已经在一个容器中,并且您尝试将其添加到另一个容器中,则该组件将从第一个容器中删除,然后添加到第二个容器中。

Solved.

Checking at the UI-Swing section of the Java Tutorial, it says.

Each GUI component can be contained only once. If a component is already in a container and you try to add it to another container, the component will be removed from the first container and then added to the second.

淡笑忘祈一世凡恋 2024-10-17 10:07:39

我认为这是不可能的。您可以做的是让多个组件共享相同的事件处理程序。所以基本上,在您的情况下,声明两个按钮并使用相同的事件处理程序方法。

I do not think that is possible. What you can do, is have is multiple components sharing the same event handler. SO basically, in your case, declare two buttons and use the same event handler method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文