Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How do I stop a JTextField from resizing?

679470Mar 16 2009 — edited Mar 16 2009
I have a JTextField that keeps resizing when its container JFrame resizes. How do I stop this from happening? I tried several different Layout (i.e. BorderLayout, FlowLayout, GridLayout, SpringLayout, etc...), but, if the JFrame resizes, then the JTextField also resizes. If I can't stop JTextField from resizing, then how do I make it so the text in JTextField is always at the top (it's always in the center vertically). Here's a SSCCE.
import java.awt.BorderLayout;
import java.awt.GridLayout;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

/**
 * Frame with label and text field.
 *
 */
public class MyTextFieldFrame extends JFrame {

	private JLabel _lbl;
	private JTextField _tf;
	
	public MyTextFieldFrame() {
		_lbl = new JLabel("Label: ");
		_lbl.setHorizontalAlignment(JLabel.RIGHT);
		
		_tf = new JTextField();
		_tf.setText("Some text...");
		
		JPanel panel = new JPanel(new GridLayout(1,2));
		panel.setBorder(BorderFactory.createTitledBorder("Test"));
		panel.add(_lbl);
		panel.add(_tf);
		
		getContentPane().setLayout(new BorderLayout());
		getContentPane().add(panel, BorderLayout.CENTER);
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		pack();
		show();
	}
	
	/**
	 * Main method.
	 * @param args
	 */
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() { 
			public void run() {
				JFrame.setDefaultLookAndFeelDecorated(true);
				new MyTextFieldFrame();
			}
		});

	}

}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 13 2009
Added on Mar 16 2009
4 comments
2,595 views