Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I keep JTextFields in a Java Swing BoxLayout from expanding?

Tags:

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.

like image 897
Matthew Avatar asked Apr 25 '10 17:04

Matthew


2 Answers

textField = new JTextField( ... ); textField.setMaximumSize( textField.getPreferredSize() ); 
like image 143
camickr Avatar answered Sep 18 '22 20:09

camickr


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) );
like image 28
cbrown Avatar answered Sep 19 '22 20:09

cbrown