3

我想用swing制作这个界面:

在此处输入图像描述

当我调整它时,我希望所有子面板和按钮都像这样调整大小:在此处输入图像描述

不仅要调整主窗口的大小。我正在使用 GridBagLayout。而且我不知道如何将带有 GridBagLayout 的面板边框以这种方式粘贴到 Frame 的边框上,当我调整框架的大小时,面板也将被调整大小。

4

2 回答 2

9

我通常为此使用嵌套布局。

  • 使用 aJPanel和 aBorderLayout作为基础。
  • 将您的中心组件存储在 aJPanel中,并将其添加CENTERBorderLayout.
  • 将底部组件存储在两个单独JPanel的 s 中。
  • JPanel使用 1 行 2 列的 GridLayout创建另一个。
  • JPanel以正确的顺序将两个 s 添加到其中。
  • 将此添加JPanelSOUTH.BorderLayout
于 2012-11-04T19:41:42.890 回答
3

实现这一点的属性,即当 JFrame 调整大小时,JPanel 也应该调整自身大小,将是GridBagConstraints.BOTH. 在我看来,您的Left JButtonRight JButton小一点。如果你真的想用GridBagLayout来实现这一点,我在这里制作了一个小示例代码来帮助你,看看并提出任何可能出现的问题:

import java.awt.*;
import javax.swing.*;

public class GridBagExample
{
    private JPanel contentPane;

    private void displayGUI()
    {
        JFrame frame = new JFrame("GridBag Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        contentPane = new JPanel();
        contentPane.setLayout(new GridBagLayout());

        JPanel centerPanel = new JPanel();
        centerPanel.setOpaque(true);
        centerPanel.setBackground(Color.CYAN);

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.anchor = GridBagConstraints.FIRST_LINE_START;
        gbc.weightx = 1.0;
        gbc.weighty = 0.9;
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        gbc.fill = GridBagConstraints.BOTH;  // appears to me this is what you wanted

        contentPane.add(centerPanel, gbc);

        JButton leftButton = new JButton("Left");
        JButton rightButton = new JButton("Right");
        gbc.gridwidth = 1;
        gbc.gridy = 1;
        gbc.weightx = 0.3;
        gbc.weighty = 0.1;

        contentPane.add(leftButton, gbc);

        gbc.gridx = 1;
        gbc.weightx = 0.7;
        gbc.weighty = 0.1;

        contentPane.add(rightButton, gbc);

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new GridBagExample().displayGUI();
            }
        });
    }
}

网格示例输出:

于 2012-11-05T05:00:25.240 回答