java – 创建一个“命令”控制台

前端之家收集整理的这篇文章主要介绍了java – 创建一个“命令”控制台前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个不寻常的问题:如何使用Swing创建“命令控制台”?

我想要的是用户键入命令的控制台,按enter键,并显示命令的输出.我不想允许用户更改“提示”和旧的输出.我在想像Windows CMD.EXE这样的东西.

我看了一个this的问题,但是它并没有回答我的问题.

解决方法

BeanShell提供了一个JConsole,一个命令行输入控制台,具有以下功能

>闪烁的光标
>命令历史
>剪切/复制/粘贴,包括使用CTRL箭头键选择
>命令完成
> Unicode字符输入
>彩色文本输出
> …它都包裹在滚动窗格中.

BeanShell JAR可从http://www.beanshell.org/download.html获得,源可以通过SVN从svn co http://ikayzo.org/svn/beanshell

有关JConsole的更多信息,请参阅http://www.beanshell.org/manual/jconsole.html

以下是在您的应用程序中使用BeanShell的JConsole的示例:

  1. import java.awt.Color;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.Reader;
  5.  
  6. import javax.swing.JFrame;
  7.  
  8. import bsh.util.GUIConsoleInterface;
  9. import bsh.util.JConsole;
  10.  
  11. /**
  12. * Example of using the BeanShell project's JConsole in
  13. * your own application.
  14. *
  15. * JConsole is a command line input console that has support
  16. * for command history,cut/copy/paste,a blinking cursor,* command completion,Unicode character input,coloured text
  17. * output and comes wrapped in a scroll pane.
  18. *
  19. * For more info,see http://www.beanshell.org/manual/jconsole.html
  20. *
  21. * @author tukushan
  22. */
  23. public class JConsoleExample {
  24.  
  25. public static void main(String[] args) {
  26.  
  27. //define a frame and add a console to it
  28. JFrame frame = new JFrame("JConsole example");
  29.  
  30. JConsole console = new JConsole();
  31.  
  32. frame.getContentPane().add(console);
  33. frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
  34. frame.setSize(600,400);
  35.  
  36. frame.setVisible(true);
  37.  
  38. inputLoop(console,"JCE (type 'quit' to exit): ");
  39.  
  40. System.exit(0);
  41. }
  42.  
  43. /**
  44. * Print prompt and echos commands entered via the JConsole
  45. *
  46. * @param console a GUIConsoleInterface which in addition to
  47. * basic input and output also provides coloured text
  48. * output and name completion
  49. * @param prompt text to display before each input line
  50. */
  51. private static void inputLoop(GUIConsoleInterface console,String prompt) {
  52. Reader input = console.getIn();
  53. BufferedReader bufInput = new BufferedReader(input);
  54.  
  55. String newline = System.getProperty("line.separator");
  56.  
  57. console.print(prompt,Color.BLUE);
  58.  
  59. String line;
  60. try {
  61. while ((line = bufInput.readLine()) != null) {
  62. console.print("You typed: " + line + newline,Color.ORANGE);
  63.  
  64. // try to sync up the console
  65. //System.out.flush();
  66. //System.err.flush();
  67. //Thread.yield(); // this helps a little
  68.  
  69. if (line.equals("quit")) break;
  70. console.print(prompt,Color.BLUE);
  71. }
  72. bufInput.close();
  73. } catch (IOException e) {
  74. e.printStackTrace();
  75. }
  76.  
  77. }
  78. }

注意:JConsole返回“;”如果您自己按Enter键.

猜你在找的Java相关文章