How to set the height and the width of a textfield in Java?

Ms. B picture Ms. B · Feb 11, 2013 · Viewed 145.2k times · Source

I was trying to make my JTextField fill the width and set a height for it but still failed. I tried adding the code setPreferredSize(new Dimension(320,200)); but still failed. Is there any way I can make my JTextField fill the width and set the height to 200 or something?

Answer

camickr picture camickr · Feb 11, 2013

You should not play with the height. Let the text field determine the height based on the font used.

If you want to control the width of the text field then you can use

textField.setColumns(...);

to let the text field determine the preferred width.

Or if you want the width to be the entire width of the parent panel then you need to use an appropriate layout. Maybe the NORTH of a BorderLayout.

See the Swing tutorial on Layout Managers for more information.