I have a JPanel that looks something like this:
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
...
panel.add(jTextField1);
panel.add(Box.createVerticalStrut(10));
panel.add(jButton1);
panel.add(Box.createVerticalStrut(30));
panel.add(jTextField2);
panel.add(Box.createVerticalStrut(10));
panel.add(jButton2);
... //etc.
My problem is that the JTextFields become huge vertically. I want them to only be high enough for a single line, since that is all that the user can type in them. The buttons are fine (they don't expand vertically).
Is there any way to keep the JTextFields from expanding? I'm pretty new to Swing, so let me know if I'm doing everything horribly wrong.
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) );
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());
set the max height. or put them in a scroll region
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);
来源:https://stackoverflow.com/questions/2709220/how-do-i-keep-jtextfields-in-a-java-swing-boxlayout-from-expanding