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
2009-02-27 14:36:28
Don't use Swing components off the EDT!
Tom Hawtin - tackline
2009-02-27 14:40:18
For the purposes of an example the EDT can kiss my a**!
MrWiggles
2009-02-27 14:46:23
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
2009-02-27 15:49:39
+1
A:
Fill the whole container? With BorderLayout?
container.add( jTextField, BorderLayout.CENTER );
Simple as that.
banjollity
2009-02-27 20:51:08