14

我想将两个 jPanel 并排添加到 JFrame 中。两个盒子是jpanels,外框是jframe在此处输入图像描述

我有这些代码行。我有一个名为 seatinPanel 的类,它扩展了 JPanel,在这个类中我有一个构造函数和一个名为 utilityButtons 的方法,它返回一个 JPanel 对象。我希望实用程序按钮 JPanel 位于右侧。我在这里的代码只在运行时显示utillityButtons JPanel。

public guiCreator()
    {
        setTitle("Passenger Seats");
        //setSize(500, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Container contentPane = getContentPane();

        seatingPanel seatingPanel1 = new seatingPanel();//need to declare it here separately so we can add the utilityButtons
        contentPane.add(seatingPanel1); //adding the seats
        contentPane.add(seatingPanel1.utilityButtons());//adding the utility buttons

        pack();//Causes this Window to be sized to fit the preferred size and layouts of its subcomponents
        setVisible(true);  
    }
4

2 回答 2

28

我推荐的最灵活的 LayoutManager 是BoxLayout

您可以执行以下操作:

JPanel container = new JPanel();
container.setLayout(new BoxLayout(container, BoxLayout.X_AXIS));

JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();

//panel1.set[Preferred/Maximum/Minimum]Size()

container.add(panel1);
container.add(panel2);

然后将容器添加到您的框架组件中。

于 2011-06-12T23:32:48.750 回答
5

您需要阅读并了解 Swing 必须提供的布局管理器。在您的情况下,了解 JFrame 的 contentPane 默认使用 BorderLayout 会有所帮助,您可以添加较大的中心 JPanel BorderLayout.CENTER 和另一个 JPanel BorderLayout.EAST。更多可以在这里找到:在容器中布置组件

编辑 1
Andrew Thompson 在您之前的帖子中的代码中已经向您展示了一些布局管理器:为什么我的按钮没有显示?. 同样,请阅读教程以更好地理解它们。

于 2011-06-12T23:27:07.113 回答