Example text in JTextField

The Text Prompt class provides the required functionality without using a custom JTextField.

It allows you to specify a prompt that is displayed when the text field is empty. As soon as you type text the prompt is removed.

The prompt is actually a JLabel so you can customize the font, foreground etc..:

JTextField tf7 = new JTextField(10);
TextPrompt tp7 = new TextPrompt("First Name", tf7);
tp7.setForeground( Color.RED );

If you can use external librairies, the Swing components from Jide software have what you are looking for; it's called LabeledTextField (javadoc) and it's part of the JIDE Common Layer (Open Source Project) - which is free. It's doing what mklhmnn suggested.


How about initialize the text field with default text and give it a focus listener such that when focus is gained, if the text .equals the default text, call selectAll() on the JTextField.