我在代码中使用MigLayout

import javax.swing.*;
import java.awt.*;
import net.miginfocom.swing.MigLayout;

public class MCVE
{
    JFrame myMainWindow = new JFrame("MCVE");

    JPanel mcvePanel = new JPanel();

    JTextField tf1 = new JTextField();
    JTextField tf2 = new JTextField();
    JTextField tf3 = new JTextField();
    JTextField tf4 = new JTextField();
    JTextField tf5 = new JTextField();

    public void runGUI()
    {
        myMainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        myMainWindow.setLayout(new GridLayout(1,1));

        createMCVEPanel();

        myMainWindow.getContentPane().add(mcvePanel);

        myMainWindow.setVisible(true);
        myMainWindow.pack();
    }

    public void createMCVEPanel()
    {
        MigLayout layout = new MigLayout("" , "[grow]");
        mcvePanel.setLayout(layout);

        mcvePanel.add(tf1,"growx, width 100:100:");
        mcvePanel.add(tf2,"growx, width 100:100:");
        mcvePanel.add(tf3,"growx, width 100:100:,wrap");
        mcvePanel.add(tf4,"growx, width 100:100:");
        mcvePanel.add(tf5,"growx, width 100:100:");
    }

    public static void main(String[] args)
    {
        MCVE mcve = new MCVE();
        mcve.runGUI();
    }
}


哪个创建布局



有没有一种方法可以自动调整组件的大小,以便产生这样的布局



不使用类似的代码

mcvePanel.add(tf1,"growx, width 100:100:, span 2");
mcvePanel.add(tf2,"growx, width 100:100:, span 2");
mcvePanel.add(tf3,"growx, width 100:100:, span 2, wrap");
mcvePanel.add(tf4,"growx, width 100:100:, span 3");
mcvePanel.add(tf5,"growx, width 100:100:, span 3");


我希望能够做到这一点,因为它对于5个JTextFields来说并不太复杂,但是对于诸如128个JTextFields这样的大量JTextFields,这并不是最有效的方法(不是我会使用这么多的JTextFields )。

最佳答案

代替使用span,使用split:

mcvePanel.add(tf1,"growx, width 100:100:, split 3");
mcvePanel.add(tf2,"growx, width 100:100:");
mcvePanel.add(tf3,"growx, width 100:100:,wrap");
mcvePanel.add(tf4,"growx, width 100:100:, split 2");
mcvePanel.add(tf5,"growx, width 100:100:");


另外,为了避免不得不进行显式包装,您可以将其设置为布局约束,而改为这样:

MigLayout layout = new MigLayout("wrap 1", "[grow]");
mcvePanel.setLayout(layout);

mcvePanel.add(tf1, "growx, width 100:100:, split 3");
mcvePanel.add(tf2, "growx, width 100:100:");
mcvePanel.add(tf3, "growx, width 100:100:");
mcvePanel.add(tf4, "growx, width 100:100:, split 2");
mcvePanel.add(tf5, "growx, width 100:100:");

09-25 21:56