Java Swing How to - Set Maximum size in BoxLayout








Question

We would like to know how to set Maximum size in BoxLayout.

Answer

import java.awt.Dimension;
//from w w w  .  j  a  v a 2 s. co  m
import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Main {

  public static void main(String[] args) {
    JFrame f = new JFrame();

    Box b = Box.createVerticalBox();

    JTextField field1 = new JTextField();
    JTextField field2 = new JTextField();
    field1.setMaximumSize(new Dimension(Integer.MAX_VALUE, field1
        .getPreferredSize().height));
    field2.setMaximumSize(new Dimension(Integer.MAX_VALUE, field2
        .getPreferredSize().height));
    b.add(field1);
    b.add(field2);

    b.add(Box.createVerticalGlue());

    f.setContentPane(b);
    f.setSize(500, 200);
    f.setVisible(true);
  }
}