Java System.in.read() vs Event Handler?

342 Views Asked by At

Assuming I have something like this:

 x= (char) System.in.read();

     if(x == 'a') {
        // Do something;
     }

How much different is it from something like:

public void handle(KeyEvent event) {
        switch (event.getCode()) {
            case A: // Do something;
            case ENTER: // Do something else;
        }
    }

I mean when should I use the first and when the second? What are the pros and cons?

1

There are 1 best solutions below

0
Stephen C On

The two approaches are getting input from the user in two different ways.

The first is reading characters from the JVM's "standard input" stream. If you ran your application without redirecting standard input, this stream is likely to be coming from the "console window" where you launched the JVM. The keystrokes on the console window are processed by the console / OS line editor until the user types ENTER. When that happens a line of characters is delivered to the input stream ready to be read by the JVM / Java application.

The second is processing keyboard events directly. However, this only works in a GUI application. It only sees the keyboard events directed at the application's window(s).


I mean when should I use the first and when the second?

Use the first in a console-based where you don't need to see characters at the instance the user presses a key.

Use the second when you have a GUI based application and you want to get input from the user interactively.

What are the pros and cons?

That is self-evident from the above. However, there are a couple additional "cons".

  • With the System.in approach:

    • The System.in stream could be coming from a file. If you need to be sure (or as sure as possible) that you are talking to a real user, use System.console() ... and check that you don't get null.
    • If you want to see the user's characters as they are typed, you need to use a 3rd-party library.
  • With the EventHandler approach:

    • This won't work on a "headless" system.
    • It is heavy-weight on the Java side as well. Something on the Java side needs to deal with key-up / key-down events, echoing, line-editing, end so on. If you are intercepting the events in your code, it may well be your code that has to do the heavy lifting.
    • I don't think there is a way to use it without launching a window. (Otherwise there would be no way for the end-use to know where the "input focus" is for the characters that he / she is typing.)