Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example text in JTextField

I am looking for a way to put example text into a swing JTextField and have it grayed out. The example text should then disappear as soon as any thing is entered into that text field. Some what similar to what stackoverflow does when a user is posting a question with the title field.

I would like it if it was already a extended implementation of JTextField so that I can just drop it in as a simple replacement. Anything from swingx would work. I guess if there is not an easy way to do this my option will probably be to override the paint method of JTextField do something that way maybe.

Thanks

like image 898
startoftext Avatar asked Feb 18 '11 17:02

startoftext


People also ask

What is the type of text in a JTextField object?

The object of a JTextField class is a text component that allows the editing of a single line text.

What method is used to read the text from a JTextField?

What method is used to read the text from a JTextField? Notice the use of JTextField 's getText method to retrieve the text currently contained by the text field. The text returned by this method does not include a newline character for the Enter key that fired the action event.

How do I getText from password field?

With the JTextField and JTextArea, the getText( ) method is used to retrieve the text that is entered by the user into the field or area. In JPasswordField, we will be using the getPassword( ) method to retrieve the entered password. In the JPasswordField class, this has been an update in Java coding.


2 Answers

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 );
like image 97
camickr Avatar answered Oct 27 '22 01:10

camickr


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.

like image 38
Daniel Teply Avatar answered Oct 26 '22 23:10

Daniel Teply