Java 当用户输入数据/擦除文本时,在 TextField 中显示/消失默认文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18103839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:25:13  来源:igfitidea点击:

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

javaswingfocustextfieldfocuslistener

提问by Shehan.W

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.

感谢您的时间。

采纳答案by mKorbel

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

我认为您正在寻找提示,请参阅

回答by Marcel H?ll

You have to implement an IF-clause to your focusLostand focusGainedListener. So do something like this:

你必须为你的focusLostfocusGained监听器实现一个 IF 子句。所以做这样的事情:

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

And for focusGained():

而对于focusGained()

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

Or something like this ;)

或类似的东西;)