What layout accepts percentages instead of values in swing?

别来无恙 提交于 2019-11-28 10:26:57
  • in reduced form GridBagLayout, but with success for your requirement 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();
            }
        });
    }
}

  • custom MigLayout

None of the JDK layouts allow you to do this directly. The BoxLayout and GridBagLayout sort of allow you do this.

With GridBagLayout you can specify a weightx/y value between 0 and 1 which tells the layout manager how to allocate extra space. So assuming that you create the components with a preferred size in a ratio of 80/20 they should be able to grow in the same ratio.

A BoxLayout is easier to use in this regard because you don't need to specify a specific constraint it just resizes in the ratio of preferred sizes.

For a simple layout manager that was designed to allow you to specify relative sizes as a simple constraint you can check out Relative Layout.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!