java中JTextField中如何在初始化的时候有灰色底字提示怎么弄啊?

我想在一个单行文本框未输入内容之前看到有文字提示,比如有一个输入账号框,框内提示:账号

就想QQ登陆界面账户密码框那样图片

把這段代碼加上就可以了,你試試 jtf2.addFocusListener(new FocusListener (){
@Override
public void focusGained(FocusEvent e) {
if("提示".equalsIgnoreCase(jtf2.getText())){
jtf2.setText("");
}

        }

        @Override
        public void focusLost(FocusEvent e) {
            if("".equals(jtf2.getText()) ){
                jtf2.setText("提示");

        }
        }

    });

楼上的是前台JS写法。

試試這個 JTextField jtf2 = new JTextField("提示",10);
jtf2.setFont(new Font("标楷体",Font.TRUETYPE_FONT|Font.ITALIC,12));

public class MyTextField extends JTextField implements FocusListener{
private int state = 0; //1->修改 0->提示
private String showText;
public MyTextField(String text,int column){
super(text,column);
showText = text;
setForeground(Color.GRAY);
addFocusListener(this);
}

public String getText(){
    if(this.state==1){
        return super.getText();
    }
    return "";
}

 @Override
public void focusGained(FocusEvent e) {
    if(state==0){
        state = 1;
        this.setText("");
        setForeground(Color.BLACK);
    }
}
@Override
public void focusLost(FocusEvent e) {
    String temp = getText();
    System.out.println(temp);
    if(temp.equals("")){
        setForeground(Color.GRAY);
        this.setText(showText);
        state = 0;
    }else{
        this.setText(temp);
    }
}

}

value="提示" onFocus="if(value==defaultValue){value='';this.style.color='#000'}" onBlur="if(!value){value=defaultValue;this.style.color='#999'}" style="color:#9999"