1

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?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Sam
  • 364
  • 2
  • 6
  • 17
  • Size is indeed determined by the `LayoutManager`. Suggestion for next time. Post actual code iso an image of code. – Robin Mar 07 '13 at 14:49
  • How did you add your layout to your frame's container? And do you even use it? You should add your items into it instead of your frame directly, like this : `frame.getContentPane().add(jtf, BorderLayout.PAGE_START);`. In any case please post more code. – Rob Mar 07 '13 at 14:51
  • @Rob I've seen the use of `getContentPane ()` many times, just like in your example. But why do some people do it like that instead of just adding the component directly to the frame ? Is there a difference ? Is there an advantage ? Is there a disadvantage ? – Radu Murzea Mar 07 '13 at 15:15
  • @Rob doesn't matter ... – kleopatra Mar 07 '13 at 15:46
  • 1
    @SoboLAN explicitly adding to the contentPane is an old habit, prior to the days when the jFrame.add method was delegated to the contentpane. Some (not me, but that's personal taste) prefer to do it even nowadays for consistency: there are only a few (those most frequently used) methods which are delegated, others are not. So if you need to use both, the code might look confusing. – kleopatra Mar 07 '13 at 15:50

1 Answers1

3

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);
Community
  • 1
  • 1
Catalina Island
  • 7,027
  • 2
  • 23
  • 42
  • regarding your linked answer: actually, hard-coding **any** of the min/pref/max is a bad idea, whatever value you use – kleopatra Mar 07 '13 at 15:45
  • Thank you for all Answers and comments. I need to go through FRAME, PANEL, CONTENT PANE AND LAYOUTS thoroughly. – Sam Mar 08 '13 at 06:45
  • 1
    @Sam: You might look at some of these [examples](http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html). – Catalina Island Mar 08 '13 at 13:33
  • @ Catalina Island:These examples look great to learn the basics.Thank you for your time. – Sam Mar 09 '13 at 05:55