在 jPasswordField 中获取等效于输入的字符串

Getting String equivalent of input in jPasswordField

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

-字段为

-使用了无效字符

如果密码是弱、中、强、非常强

,也会显示
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;
    }

但是该方法不能"check"我转换的字符串。

这是我的方法..

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]

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

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

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