How to Add Prompt Text to a Text Field in JavaFX 


               


How to Add Prompt Text to a Text Field in JavaFX

Java


In this article, we show how to add prompt text to a text field in JavaFX.

A prompt text is text that appears in a text field when it is first load but that disappears when a user starts typing into the text field.

Many professional websites use prompt texts because they are often used as kind of like hints to give a user instructions. For example, if you want a user to type in an email address, you may enter the prompt text of "Enter email address" in the text field.

As soon as the user clicks on the text field, that phrase disappears.

Again, prompt text is used a lot in the modern professional software world.

In JavaFX, we can set add prompt text to a text field using the setPromptText() function.

This is shown in the code below.



Inside of this setPromptText() function, we pass a parameter to the prompt text that we want to display. In this example, we pass in, "Enter your name". So the prompt text, "Enter your name", is shown in the text field.

What the line, text1.setFocusTraversable(false);, does is it makes the text field always focused. Focus cannot be taken off of the text field. Therefore, it always displays the prompt text. Without this line added, you will not see the prompt text unless you use the TAB key to get focus on the text field. Sometimes this is desired. Other times, this is not desired.

So the full Java code to display prompt text on a text field is shown below.





So you can see in this code, we've created a text field named text.

Then we display the prompt text, "Enter your name", through the setPromptText() function.

We then use the line, text1.setFocusTraversable(false);, so that the line will always show the prompt text even if there isn't direct focus on the line.

The code works very well.

The following link is an image of how it looks: JavaFX Prompt Text.

And this is all that is required to add prompt text to a text field in JavaFX.


Related Resources

How to Retrieve Data from a Text Field in JavaFX

How to Retrieve Data from a Radio Button Group in JavaFX

How to Retrieve Data from a Group of Check Boxes in JavaFX

How to Retrieve Data from a ChoiceBox in JavaFX

How to Retrieve Data from a ListView

How to Check if a Text Field is Empty in JavaFX

How to Select an Item By Default in JavaFX

How to Disable a Button After It's Clicked in JavaFX




HTML Comment Box is loading comments...