JLabel lblpassword = new JLabel("密码:");
JPasswordField txtpassword = new JPasswordField();
// 创建键盘适配器 匿名类
txtpassword.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
char c = e.getKeyChar();
if (c < '0' || c > '9') {
if (c != KeyEvent.VK_BACK_SPACE && c != KeyEvent.VK_ENTER) {
JOptionPane.showMessageDialog(null, "密码只能时0~9的数");
txtpassword.setText(" ");
txtpassword.requestFocus(true);
}
}
}
});
// 焦点的适配器的 匿名类
txtpassword.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
int length = txtpassword.getText().length();
if (length > 6) {
JOptionPane.showMessageDialog(null, "密码的长度最多时6位");
txtpassword.setText(" ");
txtpassword.requestFocus();
}
}
});
1、在输入框中只能输入数字、字母和下划线
2、判断长度
if(password.matches("^[\p{Alpha}\d]{6,12}$")){
//符合
}
else{
//不符合
}
只知道用正则表达式……具体的我也不会,抱歉呀