【问题标题】:How to access to the text inside a Swing JPasswordField object?如何访问 Swing JPasswordField 对象中的文本?
【发布时间】:2013-11-30 10:34:08
【问题描述】:

JFrame 类中,我有一个 JPasswordField 对象,如下所示:

pswdTextField = new JPasswordField(20);
externalPanel.add(pswdTextField, "w 90%, wrap");

我尝试通过以下代码行访问其插入的内容(用户插入的密码):

char[] pswd = pswdTextField.getPassword();
System.out.println("Password: " + pswd.toString());

问题是,当我打印此内容时,我得到以下输出:Password: [C@d5c0f9 而不是插入的密码

为什么?这是什么意思?如何获取插入的密码?

Tnx

安德烈亚

【问题讨论】:

  • "Tnx Andrea" 由 1400 代表。您应该知道不要在帖子中包含噪音。

标签: java swing user-interface jpasswordfield


【解决方案1】:

为什么?什么意思?

如果你通过docs 比你得到这个原因。

为了更强的安全性,建议返回的字符 数组在使用后通过将每个字符设置为零来清除。

如何获取插入的密码?

您可以通过以下方式获取密码,

  char[] pswd = pswdTextField.getPassword();
  String password=new String(pswd);

或者,您可以直接在System.out.print上打印

  System.out.print(pswd); // It override ...print(char[]) method
                          // without concat with another String.

编辑

请注意,如果您将char[]String 连接起来,它将继承Object.toString() 方法。

 System.out.print("Password: " +pswd);// It will print like Password: [C@d5c0f9

【讨论】:

  • 不,如果我这样做 char[] pswd = pswdTextField.getPassword(); System.out.println("密码:" + pswd);我总是获得 thsi 输出:“密码:[C@7a19a37a”
  • 但是将 char[] pswd 转换为新的 String 对象效果很好:-)
  • @AndreaNobili,没有字符串的 concat 密码,你可以打印出来。
【解决方案2】:

pswdTextField.getText() 就是你要找的。 toString() 不会返回 JPasswordField() 内的文本。

Object 类的 toString 方法返回一个字符串,该字符串由 对象是其实例的类的名称,at 符号 字符“@”和哈希的无符号十六进制表示 对象的代码。换句话说,这个方法返回一个字符串等于 的值:getClass().getName() + '@' + Integer.toHexString(hashCode())

所以使用

System.out.println("Password: " +pswdTextField.getText());

【讨论】:

  • 好的,它工作但 Eclipse 告诉我 getText() 方法已被弃用,我有什么用?
【解决方案3】:

getText() 被 JPasswordField 折旧

在Java源码中,它写在getText()定义上面

"出于安全原因,不推荐使用此方法。"

所以 getPassword() 是首选。 您面临的问题是您正在使用 System.out.println() 打印数组 要么使用该字符数组创建一个字符串 或者使用for循环逐个访问每个元素

for(int i=0;i

System.out.print(charArray[i]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 2022-11-14
    • 1970-01-01
    • 2011-09-18
    相关资源
    最近更新 更多