JTextAreaOutputStream.java 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package com.its.vds.UI;
  2. import javax.swing.*;
  3. import javax.swing.text.BadLocationException;
  4. import java.io.IOException;
  5. import java.io.OutputStream;
  6. public class JTextAreaOutputStream extends OutputStream {
  7. private final JTextArea logArea;
  8. public static boolean isLoggingPause = false;
  9. public JTextAreaOutputStream(JTextArea logArea) {
  10. if (logArea == null)
  11. throw new IllegalArgumentException ("Destination is null...");
  12. this.logArea = logArea;
  13. }
  14. public synchronized void logWrite(String text) {
  15. Runnable runnable = new Runnable() {
  16. public void run() {
  17. logArea.append(text);
  18. if (logArea.getDocument().getLength() >
  19. 50000) {
  20. try {
  21. logArea.getDocument().remove(0, 5000);
  22. } catch (BadLocationException e) {
  23. //log.error("Can't clean log", e);
  24. }
  25. }
  26. logArea.setCaretPosition(logArea.getDocument().getLength());
  27. }
  28. };
  29. SwingUtilities.invokeLater(runnable);
  30. }
  31. @Override
  32. public void write(byte[] buffer, int offset, int length) throws IOException
  33. {
  34. if (isLoggingPause) {
  35. return;
  36. }
  37. final String text = new String(buffer, offset, length);
  38. //logWrite(text);
  39. SwingUtilities.invokeLater(new Runnable ()
  40. {
  41. @Override
  42. public void run()
  43. {
  44. synchronized (logArea) {
  45. // if (logArea.getDocument().getLength() > 50000) {
  46. // try {
  47. // logArea.getDocument().remove(0,5000);
  48. // } catch (BadLocationException e) {
  49. // }
  50. // }
  51. if (logArea.getLineCount() > 500) {
  52. logArea.setText(null);
  53. }
  54. logArea.append(text);
  55. logArea.setCaretPosition(logArea.getDocument().getLength());
  56. }
  57. }
  58. });
  59. }
  60. @Override
  61. public void write(int b) throws IOException {
  62. write (new byte [] {(byte)b}, 0, 1);
  63. }
  64. }