将out和err流定向到指定流中,再将这个流显示到JTextArea

来源:互联网 发布:怎么打罗马数字mac 编辑:程序博客网 时间:2024/04/28 15:25

package debug;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class ConsoleWindow {
 public static void init() {
  JFrame frame = new JFrame();
  frame.setTitle("ConsoleWindow");
  final JTextArea output = new JTextArea();
  output.setEditable(false);
  frame.add(new JScrollPane(output));
  frame.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
  frame.setLocation(DEFAULT_LEFT, DEFAULT_TOP);
  frame.setFocusableWindowState(false);
  frame.setVisible(true);
  
  //安装一个流,将该流定向到output中
  PrintStream consoleStream = new PrintStream(new OutputStream() {
   @Override
   public void write(int b) throws IOException {
    
   }
   
   @Override
   public void write(byte[] b, int off, int len) throws IOException {
    output.append(new String(b, off, len));
   }
  });
  
  //将err和out流定向到consoleStream中
  System.setOut(consoleStream);
  System.setErr(consoleStream);
 }
 
 public static final int DEFAULT_WIDTH = 300;
 public static final int DEFAULT_HEIGHT = 200;
 public static final int DEFAULT_LEFT = 200;
 public static final int DEFAULT_TOP = 200;
}

原创粉丝点击