Files
HaE/src/main/java/hae/utils/UIEnhancer.java

45 lines
1.6 KiB
Java
Raw Normal View History

2024-05-24 15:00:49 +08:00
package hae.utils;
2024-05-23 12:00:13 +08:00
import javax.swing.*;
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
public class UIEnhancer {
public static void setTextFieldPlaceholder(JTextField textField, String placeholderText) {
2024-11-16 18:06:49 +08:00
// 使用客户端属性来存储占位符文本和占位符状态
textField.putClientProperty("placeholderText", placeholderText);
textField.putClientProperty("isPlaceholder", true);
// 设置占位符文本和颜色
setPlaceholderText(textField);
2024-05-23 12:00:13 +08:00
textField.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
2024-11-16 18:06:49 +08:00
// 当获得焦点且文本是占位符时,清除文本并更改颜色
if ((boolean) textField.getClientProperty("isPlaceholder")) {
2024-05-23 12:00:13 +08:00
textField.setText("");
textField.setForeground(Color.BLACK);
2024-11-16 18:06:49 +08:00
textField.putClientProperty("isPlaceholder", false);
2024-05-23 12:00:13 +08:00
}
}
@Override
public void focusLost(FocusEvent e) {
2024-11-16 18:06:49 +08:00
// 当失去焦点且文本为空时,设置占位符文本和颜色
2024-05-23 12:00:13 +08:00
if (textField.getText().isEmpty()) {
2024-11-16 18:06:49 +08:00
setPlaceholderText(textField);
2024-05-23 12:00:13 +08:00
}
}
});
}
2024-11-16 18:06:49 +08:00
private static void setPlaceholderText(JTextField textField) {
String placeholderText = (String) textField.getClientProperty("placeholderText");
textField.setForeground(Color.GRAY);
textField.setText(placeholderText);
textField.putClientProperty("isPlaceholder", true);
}
2024-05-23 12:00:13 +08:00
}