8

I want to add some hint text in a textfield, like "name" or "surname". I create the textfield like this TextField userTextField = new TextField(); , but I cannot find how to do that. Here, I just found this Clear prompt text in JavaFX TextField only when user starts typing but I cannot believe this is the only way to do it. Or I am wrong?

Community
  • 1
  • 1
user2556079
  • 624
  • 3
  • 9
  • 23
  • 2
    That question is about modifying the default behavior, which is that the prompt text is not visible if the text field has focus. If you need to modify that behavior, then you need to do something along those lines. If you are happy with the default behavior, just call `userTextField.setPromptText(...);`. – James_D Dec 03 '15 at 16:14
  • 1
    I already tried `TextField userTextField.setPromptText("name");` but it doesn't work. A few minutes ago I found that I have to do this `userTextField.setFocusTraversable(false);` in fact it works. – user2556079 Dec 03 '15 at 16:28
  • 1
    That call has always worked fine for me, but again you won't see the prompt text if the text field has focus. If you call `setFocusTraversable(false)`, doesn't that degrade the user experience (user cannot press "tab" to navigate to the text field)? – James_D Dec 03 '15 at 16:32
  • 1
    Yes , if the field has focus you can't see the prompt text, but I'm lucky in this situation because the UI that contains that textfield hasn't focus when it starts. Also the user doesn't need to press "tab" because that textfield is the only one present in the UI – user2556079 Dec 03 '15 at 16:38

1 Answers1

13

I do it like this:

userTextField.setPromptText("name"); //to set the hint text
userTextField.getParent().requestFocus(); //to not setting the focus on that node so that the hint will display immediately
Emanuel Graf
  • 756
  • 17
  • 37