Sam
Sam

Reputation: 374

Not able to edit width of JTextField in JFrame with Border Layout

Thank you all who helped me on JTextField Issue. I got JTextField successfully added to my frame with Border Layout by using BorderLayout.PAGE_START. But now i am not able to edit the width of JTextField .Only height is changing. Please have a look at the underlined line.[This changes height of JTextField, but width is not changing].

JFrame with fully stretched TextField

Is border layout stretches all components to its maximum width?

Upvotes: 1

Views: 1208

Answers (1)

Catalina Island
Catalina Island

Reputation: 7126

Don't use setPreferredSize() like this, because you don't know how big the font will be. Do like this instead.

Edit: I forgot about BorderLayout.PAGE_START, so just use the FlowLayout of a new JPanel(); it uses the text field's built-in preferred size.

JTextField textField = new JTextField(10);
JPanel panel = new JPanel();
panel.add(textField);
frame.add(panel, BorderLayout.PAGE_START);
...
frame.pack();
frame.setVisible(true);

Upvotes: 3

Related Questions