1

Is it possible to bind an action listener for keyboard events? E.g., I would like to write a program which computes something in the background, and when a key is pressed on the keyboard, the program executes a callback (a block of code).

Needless to say that the program is a command line program without any fancy GUI. Any short snippet will be great :)

8
  • 2
    "Needless to say that the program is a command line program" So read System.in & do whatever is appropriate on receiving new data. "Is it possible to bind an action listener for keyboard events?" not in a command-line based app. ..and what millennium is this? Add a GUI. Commented Dec 1, 2012 at 11:06
  • A console app? You could just read System.in and do whatever you want to do read character/string Commented Dec 1, 2012 at 11:10
  • gui is for weak people :) anyway, your approaches will force me to use a polling, i.e. iterate over the stream and see whether there is input on it, which spends cpu power and the method itself is blocking! Commented Dec 1, 2012 at 11:43
  • depict the following scenario -- the program is launched, checked for io redirect/pipeline, if nothing is supplied then the program continues. your approach will not allowed it. Commented Dec 1, 2012 at 11:49
  • Gui is for weak people ? So i believe right now you posted here not from stackoverflow.com but you run.a commandline app that implements stackoverflowAPI ? @MrRoth Commented Dec 1, 2012 at 11:55

2 Answers 2

1

As far as I understand you want to enable non blocking IO from console application. This cannot be done with JDK only, but fortunately there are several 3rd party libraries that enable this functionality.

Take a look on the following discussions: What's a good Java, curses-like, library for terminal applications?

How to determine if anything has been entered into the console window?

how can I detect arrow keys in java console not in GUI?

Listening to system mouse clicks from Java

Sign up to request clarification or add additional context in comments.

Comments

0

Not sure if there is a way to attach eventLinsteners to a console app,

Console app? You could just read System.in and do whatever you want to do read character/string

Scanner sc = new Scanner(System.in);
String inputString = sc.nextLine(); // you could swith it with nextInt(), nextFloat() etc based on yoir need

If(inputString.equals("whatever")
{
//do whatever , look into Runtime.exec to execute programs
}

1 Comment

please see my comment to the original post

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.