什么布局接受百分比而不是摆动中的值?

arm*_*min 4 java swing layout-manager

我需要根据他们所需的可视空间百分比来创建框架内容.例如,面板20%,面板2面板180%.这种布局管理有什么布局?

mKo*_*bel 11

  • 以简化形式GridBagLayout,但成功满足您的要求80% - 20%

.

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

public class BorderPanels extends JFrame {

    private static final long serialVersionUID = 1L;

    public BorderPanels() {
        setLayout(new GridBagLayout());// set LayoutManager
        GridBagConstraints gbc = new GridBagConstraints();
        JPanel panel1 = new JPanel();
        Border eBorder = BorderFactory.createEtchedBorder();

        panel1.setBorder(BorderFactory.createTitledBorder(eBorder, "80pct"));
        gbc.gridx = gbc.gridy = 0;
        gbc.gridwidth = gbc.gridheight = 1;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.anchor = GridBagConstraints.NORTHWEST;
        gbc.weightx = gbc.weighty = 70;
        add(panel1, gbc); // add component to the ContentPane

        JPanel panel2 = new JPanel();
        panel2.setBorder(BorderFactory.createTitledBorder(eBorder, "20pct"));
        gbc.gridy = 1;
        gbc.weightx = gbc.weighty = 20;
        gbc.insets = new Insets(2, 2, 2, 2);
        add(panel2, gbc); // add component to the ContentPane

        JPanel panel3 = new JPanel();
        panel3.setBorder(BorderFactory.createTitledBorder(eBorder, "20pct"));
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.gridwidth = 1;
        gbc.gridheight = 2;
        gbc.weightx = /*gbc.weighty = */ 20;
        gbc.insets = new Insets(2, 2, 2, 2);
        add(panel3, gbc); // add component to the ContentPane

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // important
        pack();
        setVisible(true); // important
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() { // important

            @Override
            public void run() {
                BorderPanels borderPanels = new BorderPanels();
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)
  • 习惯 MigLayout

  • 本来打算投票,但后来意识到该示例没有演示如何使用 GridBagLayout 来实现相对大小。Weightx/y 约束仅控制在调整框架大小时如何分配额外空间。每个面板的首选大小是 (10, 10),因为它使用 FlowLayout。如果将帧宽度增加 10 个像素,对于新尺寸 (18, 10) 和 (12, 10),一个面板将有 8 个像素,另一个面板将有 2 个像素,这不是总尺寸的 80/20 比率。为了使权重 x/y 发挥作用,您需要为每个已达到所需比例的面板分配首选尺寸。 (2认同)