Question

I have this code:

public static void main(String[] args) {
    JPanel panel1 = new JPanel(new MigLayout(new LC().fillX()));
    panel1.add(new JTextField("text1"), "span, grow");
    panel1.add(new JTextField("another text field"), "span, grow");
    panel1.add(new JTextField("text3"), "span, grow");

    JPanel panel2 = new JPanel(new MigLayout());
    JTextArea textArea = new JTextArea();
    textArea.setColumns(15);
    textArea.setRows(7);
    JScrollPane jsp = new JScrollPane(textArea);
    panel2.add(jsp, "span, grow");

    JFrame frame = new JFrame();
    frame.setLayout(new GridLayout(1, 2));
    frame.add(panel1);
    frame.add(panel2);

    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

which produces this:

enter image description here

But, I am trying to get the JTextFields to space out evenly.

So, I change:

JPanel panel1 = new JPanel(new MigLayout(new LC().fillX()));

to

JPanel panel1 = new JPanel(new MigLayout(new LC().fill()));

(fill() works the same as combining fillX() and fillY()) which produces:

enter image description here

However, I do not wish for the JTextFields to resize, only the gaps between them to increase. Is there a way to accomplish this with MigLayout?

Was it helpful?

Solution

I figured it out. It is because I was using the grow attribute for each component. The proper attribute to use is growx.

public static void main(String[] args) {
    JPanel panel1 = new JPanel(new MigLayout(new LC().fill()));
    panel1.add(new JTextField("text1"), "span, growx");
    panel1.add(new JTextField("another text field"), "span, growx");
    panel1.add(new JTextField("text3"), "span, growx");

    JPanel panel2 = new JPanel(new MigLayout());
    JTextArea textArea = new JTextArea();
    textArea.setColumns(15);
    textArea.setRows(7);
    JScrollPane jsp = new JScrollPane(textArea);
    panel2.add(jsp, "span, grow");

    JFrame frame = new JFrame();
    frame.setLayout(new GridLayout(1, 2));
    frame.add(panel1);
    frame.add(panel2);

    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top