Java Console Control Panel with Stop

I'm looking for a way to stop the following line from executing:

private static void cancellaaaaaaaaable() throws InterruptedException {
    System.out.println("Cancellaaaaaaable!");
    System.out.print(ANSI_RED);
    for(int i = 0; i < 79; i++){
        // Something that allows user input/interaction capable to stop the progressbar
        System.out.print("β–ˆ");
        TimeUnit.MILLISECONDS.sleep(500);
    }
    System.out.print(ANSI_RESET);
}

      

When the progress bar starts, the user should have about 40 seconds to decide to stop and cancel the progress bar.

enter image description here

Is there a way to do this? It's great for any keyboard input, except for the ones that abruptly stop the process.

+3


source to share


2 answers


Here is a solution inspired by how to read from standard input without blocking?

The idea is to check if there is something to read from System.in

.

Note that this only works if the entry is confirmed (for example with a key Enter), but blank input (key Enterpressed) works , so you can add a "Press Enter to cancel" message.



private static void cancellaaaaaaaaable() throws InterruptedException {
    System.out.println("Cancellaaaaaaable!");
    System.out.print(ANSI_RED);

    InputStreamReader inStream = new InputStreamReader(System.in);
    BufferedReader bufferedReader = new BufferedReader(inStream);
    for (int i = 0; i < 79; i++) {

        System.out.print("β–ˆ");
        TimeUnit.MILLISECONDS.sleep(500);

        // Something that allows user input/interaction capable to stop the progressbar
        try {
            if (bufferedReader.ready()) {
                break;
            }
        } catch (IOException e) {

            e.printStackTrace();
        }
    }
    System.out.print(ANSI_RESET);
}

      

Note that you can perform more complex console functions using the Java Curses Library .

+3


source


define the callee:

class MyCallable implements Callable<Boolean> {

    @Override
    public Boolean call() throws Exception {
        for (int i = 0; i <= 99; i++) {
            System.out.print("β–ˆ");
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.getStackTrace();
                return false;
            }
        }
        return true;
    }
}

      

and then FutureTask and ExecutroService:



public static void main(String[] args) throws InterruptedException {
    System.out.println("Cancellaaaaaaable!");
    MyCallable callable1 = new MyCallable();
    FutureTask<Boolean> futureTask1 = new FutureTask<>(callable1);

    ExecutorService executor = Executors.newFixedThreadPool(1);
    executor.execute(futureTask1);
    TimeUnit.MILLISECONDS.sleep(500);
    futureTask1.cancel(true);
    System.out.println("\nDone");

}

      

and reverse this when you need it:

futureTask1.cancel(true);

      

+1


source







All Articles