在 JTextFIeld 中隐藏/显示密码(Java Swing)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19755259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 19:56:06  来源:igfitidea点击:

Hide/Show Password in a JTextFIeld (Java Swing)

javaswingpasswordsjtextfield

提问by Manas Bajaj

So I've been working on a Password Strength Checker and the way it works is that the user enters some random text into a textfield and then instantaneous visual feedback (breakdown of points) is displayed. I've also added a checkbox, which on being selected, should hide the password i.e. replace all the chars with asterisks, while preserving the actual text input by the user. A document listener is being used to keep track of changes inside the textfield. (each char on entry gets analyzed and then scored)

所以我一直在研究密码强度检查器,它的工作方式是用户在文本字段中输入一些随机文本,然后显示即时视觉反馈(点细分)。我还添加了一个复选框,选中时应隐藏密码,即用星号替换所有字符,同时保留用户输入的实际文本。文档侦听器用于跟踪文本字段内的更改。(条目中的每个字符都会被分析然后评分)

So, my question is, how exactly do I mask the user input with asterisks preserving its original value?

所以,我的问题是,如何用星号屏蔽用户输入以保留其原始值?

Here's what the GUI looks like:

这是 GUI 的样子:

http://speedcap.net/sharing/screen.php?id=files/51/2f/512f9abb3f92a25add7c593e9d80e9e4.png

http://speedcap.net/sharing/screen.php?id=files/51/2f/512f9abb3f92a25add7c593e9d80e9e4.png

采纳答案by Sage

How exactly do I mask the user input with asterisks preserving its original value?

如何使用星号屏蔽用户输入以保留其原始值?

Use the JPasswordFieldwhich has nice function jPasswordField.getPassword();to get the password as char[]to work with.

使用JPasswordField具有良好功能jPasswordField.getPassword();的密码来获取密码char[]

  • Use jPasswordField1.setEchoChar('*')to mask the password characters with *.
  • If you wish to see the value you are inserting use jPasswordField1.setEchoChar((char)0);Setting a value of 0indicates that you wish to see the text as it is typed, similar to the behavior of a standard JTextField.
  • 用于jPasswordField1.setEchoChar('*')用 屏蔽密码字符*
  • 如果您希望看到您正在插入的值,请使用jPasswordField1.setEchoChar((char)0);设置值0表示您希望在键入时看到文本,类似于标准JTextField.

Tutorial and Reference:

教程和参考:

  1. How to use Password Fields
  2. setEchoChar(char)
  1. 如何使用密码字段
  2. setEchoChar(char)

回答by Mahdani Ismail

ok thanks for tutorialnya,

好的,谢谢tutorialnya,

and ex,

和前,

action chechbox / double click

动作复选框/双击

private void lihatActionPerformed(java.awt.event.ActionEvent evt) {  

   if (lihat.isSelected()) {
      password.setEchoChar((char)0); //password = JPasswordField
   } else {
      password.setEchoChar('*');
   }
}

回答by Muhammad Aasharib Nawshad

Use Password Field Instead of using textfield

使用密码字段而不是使用文本字段