Java 设置布局

Java Set Layout

我需要创建一个具有三个 JPanel 的 JFrame,如图所示:

谁能告诉我如何实现这种布局?我已经尝试使用 BorderLayout,但在 BorderLayout 中,如果我在 BorderLayout.NORTH 添加最上面的窗格,在 BorderLayout.CENTER 的中心添加窗格,在底部添加窗格到 BorderLayout.SOUTH,最上面的窗格变得太小(高度),中间的窗格变得太大(高度)。

P.S。我已经制作了 3 个窗格并正确设置了它们的首选大小。

你可以使用各种各样的东西,复合布局(例如使用两个 BorderLayout)或其他布局,这将取决于你最终想要实现的目标。

为简单起见,我将使用 GridBagLayout,例如...

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestLayout {

    public static void main(String[] args) {
        new TestLayout();
    }

    public TestLayout() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.weightx = 1;
            gbc.weighty = 1;
            gbc.fill = GridBagConstraints.BOTH;

            add(new ABigPanel(), gbc);

            gbc.weighty = 0;
            gbc.fill = GridBagConstraints.HORIZONTAL;

            add(new ASmallPanel(), gbc);
            add(new ASmallerPanel(), gbc);
        }

    }

    public class ABigPanel extends JPanel {

        public ABigPanel() {
            setBackground(Color.RED);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 200);
        }

    }

    public class ASmallPanel extends JPanel {

        public ASmallPanel() {
            setBackground(Color.GREEN);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 180);
        }

    }

    public class ASmallerPanel extends JPanel {

        public ASmallerPanel() {
            setBackground(Color.CYAN);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 40);
        }

    }

}

有关详细信息,请参阅 How to Use GridBagLayout