我有一个包含大量上下文的 JPanel。
我希望能够将上述 JPanel 添加到两个 JFrames。有什么建议吗?
这是我想要的例子
public class Test
{
public static void main(String [] args)
{
JPanel panel = new JPanel();
panel.add(new JLabel("Hello world"));
panel.validate();
JFrame frame1, frame2;
frame1 = new JFrame("One");
frame2 = new JFrame("Two");
frame1.add(panel);
frame2.add(panel);
frame1.validate();
frame2.validate();
frame1.setVisible(true);
frame2.setVisible(true);
frame1.pack();
frame2.pack();
}
}
我希望两个 JFrames 都显示 hello world,而不是一个显示它而另一个为空。如果 JPanel 中的数据更新,我希望两个 JFrames 都显示它。
感谢任何人的帮助,这已经困扰我一段时间了。
最佳答案
我认为你做不到。当您向其中添加 Component
时,java.awt.Container
中的代码包含此花絮。在这里,阅读 Container
的 JFrame
和 comp
的 JPanel
:
/* Reparent the component and tidy up the tree's state. */
if (comp.parent != null) {
comp.parent.remove(comp);
if (index > component.size()) {
throw new IllegalArgumentException("illegal component position");
}
}
(在 java.awt.Container.addImpl(Component, Object, int)
中)
就在那里,当您将它添加到不同的 Container
时,它会从旧的 Container
中删除它。我想您可以重写这个基本级别的 AWT 代码,但我不推荐这样做。
关于java - 将 JPanel 添加到多个 JFrames,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20225868/