I have a JPanel
that looks something like this:
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
...
pane
JPanel panel = new JPanel();
Box box = Box.createVerticalBox();
JTextField tf = new JTextField(8);
box.add(tf);
panel.add(box);
frame.getContentPane().add(panel, BorderLayout.CENTER);
set the max height. or put them in a scroll region
In my case I need a combination of all the answers for it to work properly. If I don't use glue, it is not centered vertically; if I don't restrict maximum size, it extends vertically; if I restrict both width and height, it is too small, being only wide enough to contain the initialization text.
textField = new JTextField("Hello, world!");
textField.setMaximumSize(
new Dimension(Integer.MAX_VALUE,
textField.getPreferredSize().height));
Box box = Box.createVerticalBox();
box.add(Box.createVerticalGlue());
box.add(textField);
box.add(Box.createVerticalGlue());
textField = new JTextField( ... );
textField.setMaximumSize( textField.getPreferredSize() );
If you want the width to keep changing, just keep it set to MAX INT. So...
textField.setMaximumSize( new Dimension(Integer.MAX_VALUE, textField.getPreferredSize().height) );