如何在1个JPanel中获得2个JPanels,可调整大小,具有固定比例?

时间:2014-11-12 03:53:09

标签: java swing user-interface layout-manager

假设JFrame只包含1 JPanel。此JPanel分为2 JPanel个,相应地占据0.75高度的0.25JFrame。我希望所有这些都可以与窗口大小一起调整。

我不知道如何在Java中这样做。

我是Java的新手。我已经阅读了一些关于布局的内容,但我只能看到如何在构造函数中设置首选大小(当达到此数字时停止调整大小)或通过设置边框获得一些固定大小。

1 个答案:

答案 0 :(得分:4)

带有JFrame

BorderLayout,添加JPanel GridBagLayout。将其他两个面板添加到此。

有关详细信息,请参阅Laying Out Components Within a ContainerHow to Use GridBagLayout

Resizable

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.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

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

    public Test() {
        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.gridx = 0;
            gbc.gridy = 0;
            gbc.fill = GridBagConstraints.BOTH;
            gbc.weightx = 1;
            gbc.weighty = 0.75;

            JPanel top = new JPanel(new GridBagLayout());
            top.add(new JLabel("Top"));
            top.setBackground(Color.RED);
            add(top, gbc);

            gbc.gridy++;
            gbc.weighty = 0.25;

            JPanel bottom = new JPanel(new GridBagLayout());
            bottom.add(new JLabel("Bottom"));
            bottom.setBackground(Color.BLUE);
            add(bottom, gbc);

        }

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

    }

}