请注意,在 GUI 中执行此操作实际上比使用Scanner
IMOP 执行此操作要容易得多。
一种方法Scanner
是使用一个线程在输入字符时擦除它们并用 * 替换它们
EraserThread.java
import java.io.*;
class EraserThread implements Runnable {
private boolean stop;
/**
*@param The prompt displayed to the user
*/
public EraserThread(String prompt) {
System.out.print(prompt);
}
/**
* Begin masking...display asterisks (*)
*/
public void run () {
stop = true;
while (stop) {
System.out.print("\010*");
try {
Thread.currentThread().sleep(1);
} catch(InterruptedException ie) {
ie.printStackTrace();
}
}
}
/**
* Instruct the thread to stop masking
*/
public void stopMasking() {
this.stop = false;
}
}
密码字段.java
public class PasswordField {
/**
*@param prompt The prompt to display to the user
*@return The password as entered by the user
*/
public static String readPassword (String prompt) {
EraserThread et = new EraserThread(prompt);
Thread mask = new Thread(et);
mask.start();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String password = "";
try {
password = in.readLine();
} catch (IOException ioe) {
ioe.printStackTrace();
}
// stop masking
et.stopMasking();
// return the password entered by the user
return password;
}
}
主要方法
class TestApp {
public static void main(String argv[]) {
String password = PasswordField.readPassword("Enter password: ");
System.out.println("The password entered is: "+password);
}
}
我已经对其进行了测试,并且正在为我工作。
更多信息: