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!

JTextField does not resize properly if text not default size

843806Nov 23 2008 — edited Nov 23 2008
Hello, if the text in the JTextField is not the default size, it appears that the field does not resize properly. Here is an example: on the left is the field with default size (height 12 for my look and feel - metal on XP) "80", and on the right, the same with size 11. If you click in between 8 and 0 and delete the 0 and insert something in its place, the 8 will move a little out of the field and it will look like a "3" - only in the field with non-default size though (and it is smaller too, which should make it "easier" to enclose).

How can I have smaller size and still resize properly?? Here is the code - isolated to the minimum possible, compiles and runs
import javax.swing.*;
import javax.swing.event.*;

public class Foobar
{
	public static void main(String[] args)
	{
		JFrame frame = new JFrame();
		JPanel panel = new JPanel();
		frame.setContentPane(panel);
		FoobarTxtField normal = new FoobarTxtField("80");
		panel.add(normal);
		FoobarTxtField small = new FoobarTxtField("80");
		small.setFont(small.getFont().deriveFont((float)11));
		panel.add(small);
		frame.pack();
		frame.setVisible(true);
	}
}

class FoobarTxtField extends JTextField implements DocumentListener
{

	FoobarTxtField(String s)
	{
		super(s);
		getDocument().addDocumentListener(this);
	}

	public void insertUpdate(DocumentEvent e)
	{
		SwingUtilities.getRootPane(this).revalidate();
	}

	public void removeUpdate(DocumentEvent e)
	{
	}
	public void changedUpdate(DocumentEvent e)
	{
	}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 21 2008
Added on Nov 23 2008
2 comments
758 views