使用哪种布局?

时间:2012-11-04 19:34:17

标签: java swing layout layout-manager border-layout

我想摆动这个界面:

enter image description here

当我确定它时,我想要调整所有子面板和按钮的大小:enter image description here

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

2 个答案:

答案 0 :(得分:9)

我通常使用嵌套布局。

  • 使用JPanel作为基础BorderLayout
  • 将您的核心组件存储在JPanel中,并将其添加到CENTER的{​​{1}}。
  • 将您的底部组件存储在两个单独的BorderLayout中。
  • 使用1行和2列的GridLayout创建另一个JPanel
  • 以正确的顺序将两个JPanel添加到其中。
  • 将此JPanel添加到JPanel。{/ li>的SOUTH

答案 1 :(得分:3)

要实现这一目标的属性,即在调整JFrame大小时,JPanel也应调整自身大小,将为GridBagConstraints.BOTH。在我看来,你的左JButton 右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();
            }
        });
    }
}

GRIDBAGEXAMPLE OUTPUT :