本文最后更新于:5 个月前
JPasswordField实现原理基本和JTextField相同,实际上JPasswordField是JTextField的子类,这里有有一点需要注意,当我们不需要明文是需要设置此setEchoChar(echo)方法.
注意:这里需要考虑初始化始根据需要进行第一次赋值处理
JPasswordField中setEchoChar(echo)方法实现 ↓↓
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
public void setEchoChar(char c) { echoChar = c; echoCharSet = true; repaint(); revalidate(); }
|
代码实现如下
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
| String emptyText = "等待输入..."; char echo = 0;
JPasswordField jPasswordField = new JPasswordField();
jPasswordField.setText(emptyText);
jPasswordField.setForeground(Color.DARK_GRAY)
jPasswordField.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { if (emptyText.equals(jPasswordField.getText())) { jPasswordField.setText(""); jPasswordField.setForeground(Color.BLACK); jPasswordField.setEchoChar('*') } } @Override public void focusLost(FocusEvent e) { if (jPasswordField.getText().isEmpty() && !emptyText.isEmpty()) { jPasswordField.setText(emptyText); jPasswordField.setForeground(Color.DARK_GRAY); jPasswordField.setEchoChar(echo) } } });
|
颜色可以根据需要修改,通过失焦聚焦逻辑实现等待输入提示效果