tags:

views:

1191

answers:

4

I have a Java program, in which, I'm using a JTextField, but if i don't specify a default size, it'll have the width 0. I'm inserting it in a BorderLayout, so how do I make it expand to fill the whole container?

A: 

It will automatically fill to the width of the container, example shown:

    import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JTextField;


public class TextFieldTest {
    public static void main(String[] args) {
     JFrame f = new JFrame();
     f.setLayout(new BorderLayout());
     JTextField tf = new JTextField();
     f.add(tf, BorderLayout.SOUTH);
     f.pack();
     f.setVisible(true);
    }
}
MrWiggles
Don't use Swing components off the EDT!
Tom Hawtin - tackline
For the purposes of an example the EDT can kiss my a**!
MrWiggles
A: 

In the above example, the text field will work fine. However, if you insert into EAST or WEST, it will not work.

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JTextField;


public class TextFieldTest {
    public static void main(String[] args) {
        JFrame f = new JFrame();
        f.setLayout(new BorderLayout());
        JTextField tf = new JTextField();
        f.getContentPane().add(BorderLayout.EAST, tf);
        f.pack();
        f.setVisible(true);
    }
}

My question back to you is: Does this need to be a BorderLayout or can you use other Layout Managers? If you can, you should check out GridBagLayout that you can have an element auto expand (using a weight) to fit the entire container.

Ascalonian
I got the accepted answer without any votes? Niiiice!
Ascalonian
A: 

When programming with Swing the key thing is to use a good layout manager. For me the perfect layout manager is MigLayout. This is simply the best one-stop solution to all layout needs. Their site provides excellent documentation and examples.

01es
+1  A: 

Fill the whole container? With BorderLayout?

container.add( jTextField, BorderLayout.CENTER );

Simple as that.

banjollity