调整组件大小以适应行

Resizing components to fit the row

我在我的代码中使用 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 来说并不太复杂,但对于大量的 JTextFields,例如 128 个 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:");