java 控制台退格_在Java控制台中退格?

请注意,在GUI中执行此操作实际上比使用Scanner IMOP更容易。

使用Scanner执行此操作的一种方法是使用一个线程在输入时删除字符并将其替换为*'s

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;

}

}passwordfield.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);

}

}我已经测试了它并且正在为我工​​作。

更多信息:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值