Package GUI

Source Code of GUI.OutputStream

package GUI;

import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;

public class OutputStream extends PrintStream {
 
  private JTextPane area;
  private OutputType type;
  private Style style;
  
    public OutputStream(JTextPane area, OutputType type) {
        super(new ByteArrayOutputStream( ));
        this.area = area;
        this.type = type;
       
        setStyle();
    }

    private void setStyle() {
        StyledDocument doc = this.area.getStyledDocument();
        Style defaultStyle = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
        switch (type) {
    case ERROR:
      style = doc.addStyle("error",defaultStyle);
      StyleConstants.setForeground(style,Color.RED);
      break;
    case NORMAL:
      style = doc.addStyle("normal",defaultStyle);
      StyleConstants.setForeground(style,Color.BLACK);
      break;
    case CONSOLE:
      style = doc.addStyle("console",defaultStyle);
      StyleConstants.setForeground(style,Color.BLUE);
      break;
    default:
      break;
    }
    }
   
    @Override
  public void write(byte[] buf, final int off, final int len) {
      if (!enabled) return;
    final byte[] buf2 = Arrays.copyOf(buf, buf.length);
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        try {
          area.getDocument().insertString(area.getDocument().getLength(),new String(buf2, off, len), style);
        } catch (BadLocationException e) {
          e.printStackTrace();
        }
      }
    });
    }
   
    private boolean enabled=true;

  public boolean isEnabled() {
    return enabled;
  }

  public void setEnabled(boolean enabled) {
    this.enabled = enabled;
  }

}

enum OutputType {
  ERROR,
  NORMAL,
  CONSOLE;
}
TOP

Related Classes of GUI.OutputStream

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.