James Fazio
James Fazio

Reputation: 6450

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)); 

Upvotes: 1

Views: 7843

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285450

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);

Upvotes: 7

Related Questions