0

我有一个代码可以检查用户输入是否仅为字母数字,并根据标准检查输入的密码强度。如果出现以下情况,则会出现一个带有注释的标签:

- 字段为

-使用了无效字符

如果密码是弱、中、强非常强,也会显示

this.AlphaNumericOnly(this.jTextField1.getText(),this.warningLbl3);
this.passwordStrength(this.jTextField1.getText(),this.warningLbl4);

如果在 jtextfield 中使用,此方法可以正常工作。但是我想使用 jpasswordfield 来隐藏用户输入。

我已经尝试过:

.toString();

String.valueOf();

这个循环:

char[] input=(this.jPasswordField1.getPassword());
 final_pass = "";
    for(char x : input) {
     final_pass += x;
    }

但是该方法无法“检查”我转换的字符串。

这是我的方法..

public void AlphaNumericOnly(String input,JLabel obj){
if(!"".equals(input)){
    obj.setText(" ");
    warning=false;

    char c[] = input.toCharArray();

    int count = 0;
    for(int x=0; x<c.length; x++){
        if((!Character.isAlphabetic(c[x]))&&(!Character.isDigit(c[x]))){// && c[x]!='-' && c[x]!='(' && c[x]!=')' && c[x]!='+'&& c[x]!='/'&& c[x]!='\\'){
            count=+1;        
        }
    }
    if(count>0){
        obj.setText("*Please use valid characters.");
        warning=true;
    }else{
        obj.setText(" ");
        warning=false;
    }
}else{
    obj.setText("*This Field cannot be left Empty.");
    warning=true;
}   
}
private void passwordStrength(String input,JLabel obj){
   char c[] = input.toCharArray();
   int count=0;
   int notAlphaNumericCount=0;
   for(int j=0;j<c.length;j++){
       if(Character.isAlphabetic(c[j])){
            if(Character.isUpperCase(c[j])){
                count++;
            }
       }else if(Character.isDigit(c[j])){

       }else{
         obj.setText(" ");
         warning=false;
         notAlphaNumericCount++;
       }
   }
if(notAlphaNumericCount==0){   
    if(input.length()<1){
        obj.setText(" ");
        warning=false;
    }else if(input.length()<4){
        obj.setText("Password Strength: WEAK");
        obj.setForeground(Color.red);
    }else if(input.length()<8){
        obj.setText("Password Strength: MEDIUM");
        obj.setForeground(Color.blue);
    }else if(input.length()<10){
        obj.setText("Password Strength: STRONG");
        obj.setForeground(Color.green);
    }else if(count!=0){    
        obj.setText("Password Strength: VERY STRONG");
        obj.setForeground(Color.orange);
    }
}
}

编辑: 为了更直观地理解这里是我如何使用这种方法:

username [Textfield input]- [obj label warning]
password [Textfield input]- [obj label warning]

          [obj label which displays password strength]
4

1 回答 1

1

好吧,因为函数的返回值getPassword()是char数组。您可以通过其构造函数轻松地将其转换为字符串。

new String(this.jPasswordField1.getPassword());

不过,就个人而言,我认为将passwordStrength方法的参数更改为采用 char 数组而不是 String 会更好。因为您只使用参数input将其转换为 char 数组并获取其长度。而且,每次通过这种方式构造 String 时,都会创建一个新的 String 对象。

于 2015-08-06T09:46:54.063 回答