在 2 个不同的 JFrames 上使用相同的 JToolBar

Using the same JToolBar on 2 different JFrames

此示例创建 ToolBar 并尝试将相同的 ToolBar 添加到 2 个不同的 JFrame。

我原以为两个 JFrame 都具有相同的 ToolBar,但显然 ToolBar 仅被添加到第二个 JFrame。

如果第二个 JFrame 的代码被注释掉,那么 ToolBar 将按预期添加到第一个框架。

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import javax.swing.*;

public class ToolBarSample {
public static void main(final String args[]) {
JFrame frame = new JFrame("JToolBar Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JToolBar toolbar = new JToolBar();
toolbar.setRollover(true);


JButton button = new JButton("button");
toolbar.add(button);
toolbar.addSeparator();

toolbar.add(new JButton("button 2"));
toolbar.add(new JButton("button 3"));
toolbar.add(new JButton("button 4"));
Container contentPane = frame.getContentPane();
contentPane.add(toolbar, BorderLayout.NORTH);
contentPane.setPreferredSize(new Dimension(10,10));
JTextArea textArea = new JTextArea();
JScrollPane pane = new JScrollPane(textArea);
contentPane.add(pane, BorderLayout.CENTER);
frame.setSize(500, 500);
frame.setVisible(true);


JFrame frame2 = new JFrame("JToolBar Example 2");
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane2 = frame2.getContentPane();
contentPane2.add(toolbar, BorderLayout.NORTH);
frame2.setSize(500, 500);
frame2.setVisible(true);

}
}

为什么 JToolBar 只被添加到第二个 JFrame 而不是两者?

您只能同时将一个JToolbar(Component)添加到1个JFrame(Container)中。因为 Swing/AWT 组件的结构是一棵树。一棵树的节点不能有超过 1 个父节点。 在您的情况下,您可以实现一种创建 JToolbar 的方法。然后,您创建 2 个 JToolbar 并添加到 2 个 JFrame,如下所示:

class ToolBarSample {
    public static void main(final String args[]) {
        JFrame frame = new JFrame("JToolBar Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


        Container contentPane = frame.getContentPane();
        contentPane.add(createToolbar(), BorderLayout.NORTH);
        contentPane.setPreferredSize(new Dimension(10, 10));
        JTextArea textArea = new JTextArea();
        JScrollPane pane = new JScrollPane(textArea);
        contentPane.add(pane, BorderLayout.CENTER);
        frame.setSize(500, 500);
        frame.setVisible(true);


        JFrame frame2 = new JFrame("JToolBar Example 2");
        frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container contentPane2 = frame2.getContentPane();
        contentPane2.add(createToolbar(), BorderLayout.NORTH);
        frame2.setSize(500, 500);
        frame2.setVisible(true);

    }

    private static JToolBar createToolbar() {
        JToolBar toolbar = new JToolBar();
        toolbar.setRollover(true);


        JButton button = new JButton("button");
        toolbar.add(button);
        toolbar.addSeparator();

        toolbar.add(new JButton("button 2"));
        toolbar.add(new JButton("button 3"));
        toolbar.add(new JButton("button 4"));
        return toolbar;
    }
}