Search code examples
javaswingfocustextfieldfocuslistener

Display/disappear default text in TextField when user enters data/erase the text


I am trying to make a registration form and what i am trying to do is display a default text in text fields, simple meaning something like the below image. What i am trying to do is , until the user enters data to a field for a example there is a field called "First Name". When the user selects the field "First Name" text disappears and the user can type their First Name. IF the user doesn't type anything, the text should display again in the text field.

I tried using the focus listener, but i couldn't really get it to work because with my method even if the user types data to the field and go to the next field , the text of the previous field gets deleted and the default text gets displayed.

Here is what i have done :-

txtFirstName.addFocusListener(new FocusListener() {
    public void focusGained(FocusEvent e) {
        txtFirstName.setText("");
    }

    public void focusLost(FocusEvent e) {
        txtFirstName.setText("First Name");
    }
});

What i am trying to do

Thank you for your time.


Solution

  • What i am trying to do is , until the user enters data to a field for a example there is a field called "First Name". When the user selects the field "First Name" text disappears and the user can type their First Name. IF the user doesn't type anything, the text should display again in the text field.

    I think that you looking for prompt, see