jinlin
2025-03-18 d30e385951ce03335a5023f0775fd144da3c0b88
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.example.client.utils;
import java.awt.Color;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
 
import javax.swing.JTextField;
 
public class JTextFieldHintListener implements FocusListener {
    private String hintText;
    private JTextField textField;
    public JTextFieldHintListener(JTextField jTextField,String hintText) {
        this.textField = jTextField;
        this.hintText = hintText;
        jTextField.setText(hintText);  //默认直接显示
        jTextField.setForeground(Color.GRAY);
    }
 
    @Override
    public void focusGained(FocusEvent e) {
        //获取焦点时,清空提示内容
        String temp = textField.getText();
        if(temp.equals(hintText)) {
            textField.setText("");
            textField.setForeground(Color.BLACK);
        }
 
    }
 
    @Override
    public void focusLost(FocusEvent e) {
        //失去焦点时,没有输入内容,显示提示内容
        String temp = textField.getText();
        if(temp.equals("")) {
            textField.setForeground(Color.GRAY);
            textField.setText(hintText);
        }
 
    }
 
}