java控制台不出现_java – 在JTextArea而不是控制台上显示数据

该问题的解决方案是将System.{in,out,err}重定向到JTextArea.

>从System.out开始,使用System.setOut方法将其重定向到JTextArea组件非常简单.在下面的例子中,我使用管道和SwingWorker完成了这项工作,但这实际上是使得输出更简单的摆动组件.

>仿真System.in是类似的,您需要使用System.setIn将键击重定向到System.in.再次,在下面的示例中,我使用管道来获得更好的界面.我也缓冲线(就像“普通”控制台一样)直到你按下回车键. (请注意,例如箭头键不起作用,但它也不应该用于处理/忽略它.)

下面的屏幕截图中的文本是通过对“普通”System.out.print ..方法的多次调用,然后使用扫描程序等待System.in上的输入产生的:

public static JTextArea console(final InputStream out, final PrintWriter in) {

final JTextArea area = new JTextArea();

// handle "System.out"

new SwingWorker() {

@Override protected Void doInBackground() throws Exception {

Scanner s = new Scanner(out);

while (s.hasNextLine()) publish(s.nextLine() + "\n");

return null;

}

@Override protected void process(List chunks) {

for (String line : chunks) area.append(line);

}

}.execute();

// handle "System.in"

area.addKeyListener(new KeyAdapter() {

private StringBuffer line = new StringBuffer();

@Override public void keyTyped(KeyEvent e) {

char c = e.getKeyChar();

if (c == KeyEvent.VK_ENTER) {

in.println(line);

line.setLength(0);

} else if (c == KeyEvent.VK_BACK_SPACE) {

line.setLength(line.length() - 1);

} else if (!Character.isISOControl(c)) {

line.append(e.getKeyChar());

}

}

});

return area;

}

以及示例主要方法:

public static void main(String[] args) throws IOException {

// 1. create the pipes

PipedInputStream inPipe = new PipedInputStream();

PipedInputStream outPipe = new PipedInputStream();

// 2. set the System.in and System.out streams

System.setIn(inPipe);

System.setOut(new PrintStream(new PipedOutputStream(outPipe), true));

PrintWriter inWriter = new PrintWriter(new PipedOutputStream(inPipe), true);

// 3. create the gui

JFrame frame = new JFrame("\"Console\"");

frame.add(console(outPipe, inWriter));

frame.setSize(400, 300);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

// 4. write some output (to JTextArea)

System.out.println("Hello World!");

System.out.println("Test");

System.out.println("Test");

System.out.println("Test");

// 5. get some input (from JTextArea)

Scanner s = new Scanner(System.in);

System.out.printf("got from input: \"%s\"%n", s.nextLine());

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值