Question

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.

Was it helpful?

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

OTHER TIPS

You have to implement an IF-clause to your focusLost and focusGained Listener. So do something like this:

public void focusLost(FocusEvent e) {
        if(txtFirstName.getText().trim().equals(""))
           txtFirstName.setText("First Name");
        else
           //do nothing
    }

And for focusGained():

public void focusGained(FocusEvent e) {
        if(txtFirstName.getText().trim().equals("First name"))
           txtFirstName.setText("");
        else
           //do nothing
    }

Or something like this ;)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top