Search code examples
javaswinguser-interfacejtextfield

Java GUI specifying width of a textField


I have a BorderLayout with layouts in the North, West and Center components. Here is my problem: I have a textField in my Center component and it extends the entire width of the it's parent layout.

It looks something like this...

===============================================================================
|                                                                             |
|                                NORTH                                        |
===============================================================================
|    WEST     |                  CENTER                                       |
|             | textField: __________________________________________________ |

I want to make it so the textField does not extend the entire layout but has a fixed size and is centered within the center component.

I have tried setting the preferredSize but had no luck. Code below...

  rText = new JTextField("1000"); 
  rText.setPreferredSize(new Dimension(20, 10)); 

Solution

  • To center the JTextField, put it into its own JPanel, that uses the default FlowLayout and add that do the (I think) BorderLayout using container. To give the JTextField a good width, give it a column size when constructing it. Do not set its preferredSize as that won't behave well on different platforms. i.e.,

    rText = new JTextField("1000", 10);