3

Is there a way you can backspace and delete some letters / words a user has typed in?

I am creating a word scrambler game and before I make it GUI I am doing some console stuff. Since I am using a Scanner when the first player enters a word it stays there. So the second player can just look at it when guessing the scrambled word.
Is there anyway to remove that word from the console? Or make it show up as * * * *?
I would prefer not to have System.out.println("\n\n\n....");
That would make the input appear at the bottom and I would like it at the top. Can I remove that would the user entered or make it appear as * * * * * *?
Thanks. :)

Frank Visaggio
  • 3,642
  • 9
  • 34
  • 71
Henry Harris
  • 620
  • 4
  • 7
  • 18

1 Answers1

1

Please be advised doing this in a GUI is actually a lot easier than doing it with a Scanner IMOP.

One way to do it with Scanner is to have a thread that erase the characters as they are being entered and replace them with *'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;
   }
}

main method

class TestApp {
   public static void main(String argv[]) {
      String password = PasswordField.readPassword("Enter password: ");
      System.out.println("The password entered is: "+password);
   }
}

I've tested it and is working for me.

More information:

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Frank Visaggio
  • 3,642
  • 9
  • 34
  • 71