Resizing components to fit the row

124 views Asked by At

I am using MigLayout in my code

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();
    }
}

Which creates the layout

3x2

Is there a way to automatically resize the components so that it produces a layout like this

3xSpread2

Without using code like

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");

I would like to be able to do this because it is not too complex for 5 JTextFields but it would not be the most efficient way to do it for a larger amount of JTextFields such as 128 JTextFields (not that I would be using this many JTextFields).

1

There are 1 answers

0
Amber On BEST ANSWER

Instead of using span use 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:");

Also, to save yourself from having to wrap explicitly you could set it as a layout constraint and do it like this instead:

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:");