但是我看网上的解决办法都太过繁琐,下面写个简单的实现方式
astigmatismLeftEye = new JTextField();
astigmatismLeftEye.setBounds(677, 182, 120, 30);
astigmatismLeftEye.setBorder(null);
astigmatismLeftEye.setOpaque(false); // 设置透明
astigmatismLeftEye.setEditable(false);// 设置不可编辑
astigmatismLeftEye.setToolTipText("左眼散光");
astigmatismLeftEye.addMouseListener(this); // 添加鼠标事件
/**
* 设置散光的placeholder属性
*/
private void checkAstPlaceholder() {
// 使用数组装载输入框对象,多个输入框需要这个属性故使用数组
JTextField[] ts = {astigmatismLeftEye,astigmatismRightEye,astigmatismLeft2Eye,astigmatismRight2Eye};
// 循环检验文本内容
for (int i = 0;i<ts.length;i++)
checkText(ts[i]);
}
/**
* 校验内容是否为空,如果为空,则设置placeholder属性
* @param textField
*/
private void checkText(JTextField textField) {
// 判断输入框里是否有内容,没有就进行默认设置
if (textField.getText() == null||"".equals(textField.getText())) {
// 提示内容
textField.setText(RemindConstant.PLACE_INPUT_AST);
textField.setFont(new Font("仿宋",Font.ITALIC,14));
}
}
常量类
3. 设置事件,前面已经添加鼠标事件,下面才是重头戏
// 鼠标移入事件
@Override
public void mouseEntered(MouseEvent e) {
Object source = e.getSource();
if (source == astigmatismLeftEye) {
String text = astigmatismLeftEye.getText();
if (text.equals(RemindConstant.PLACE_INPUT_AST)) { // 移入时,如果是提示内容,则清空
astigmatismLeftEye.setText("");
}
}
if (source == astigmatismRightEye) {
String text = astigmatismRightEye.getText();
if (text.equals(RemindConstant.PLACE_INPUT_AST)) {
astigmatismRightEye.setText("");
}
}
if (source == astigmatismLeft2Eye) {
String text = astigmatismLeft2Eye.getText();
if (text.equals(RemindConstant.PLACE_INPUT_AST)) {
astigmatismLeft2Eye.setText("");
}
}
if (source == astigmatismRight2Eye) {
String text = astigmatismRight2Eye.getText();
if (text.equals(RemindConstant.PLACE_INPUT_AST)) {
astigmatismRight2Eye.setText("");
}
}
}
// 鼠标移出事件
@Override
public void mouseExited(MouseEvent e) {
Object source = e.getSource();
if (source == astigmatismLeftEye) {
String text = astigmatismLeftEye.getText();
if (text == null||"".equals(text)) { // 移出时没有发现内容,则设置为提示内容
astigmatismLeftEye.setText(RemindConstant.PLACE_INPUT_AST);
}
}
if (source == astigmatismRightEye) {
String text = astigmatismRightEye.getText();
if (text == null||"".equals(text)) {
astigmatismRightEye.setText(RemindConstant.PLACE_INPUT_AST);
}
}
if (source == astigmatismLeft2Eye) {
String text = astigmatismLeft2Eye.getText();
if (text == null||"".equals(text)) {
astigmatismLeft2Eye.setText(RemindConstant.PLACE_INPUT_AST);
}
}
if (source == astigmatismRight2Eye) {
String text = astigmatismRight2Eye.getText();
if (text == null||"".equals(text)) {
astigmatismRight2Eye.setText(RemindConstant.PLACE_INPUT_AST);
}
}
}
不懂得看看注释吧,注释写的详细。
这样placeholder属性就实现了,是不是很简单?