Is it possible to print text that can be edited by the user (for console programs)?

六眼飞鱼酱① 提交于 2019-11-29 15:36:03

No, not using only what Java provides in the framework. Editing some text would require to

  1. act on key press, which is not possible as in Java the input is buffered (i.e., wait for Enter to be pressed)
  2. to move around in the text you output, which is also not possible

This could be done using some native code (ncurse on linux, ...), using JNI or JNA, but not that easily.

Note that there are some projects that aim to add those functionalities, so if you can use something outside of the core libraries, you could give them a tries... for instance http://code.google.com/p/java-console-api/

There are various options for this, in order of simplicity and portability to features and complexity:

  1. Simply prompt for the information, reading a complete (return-terminated) line of response, and allow the normal terminal input facilities to be used for basic editing.

  2. Use something like the gnu readline library to allow more advanced editing. You still won't have widgets (text input boxes at specific places on screen) as such though. There's a java implementation here: http://java-readline.sourceforge.net/

  3. Use something like ncurses to specifically position the cursor, print text labels, handle keypresses, and implement your own text input box. Not fun.

  4. Use a textual user interface library (TUI), like this one: http://www.bmsi.com/tuipeer/

If you opened a window that looks like the console window, and could react to keypress events, then you could do what you are asking, but, otherwise, if you are just running a program, the program will have ceased executing and returned control to your console, so it can't do anything else.

But, if you use a scriptable version of java you could write your own shell, and then you could do what you are asking, as the shell would not cease executing.

But, that will probably be beyond your course.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!