Dépôt du be graphe
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

StreamCapturer.java 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package org.insa.graphs.gui;
  2. import java.io.IOException;
  3. import java.io.OutputStream;
  4. import javax.swing.JTextArea;
  5. public class StreamCapturer extends OutputStream {
  6. private StringBuilder buffer;
  7. private String prefix = null;
  8. private JTextArea output;
  9. /**
  10. * @param output Output JTextArea to which this stream should print.
  11. * @param prefix Prefix to add to each line of this output.
  12. */
  13. public StreamCapturer(JTextArea output, String prefix) {
  14. this.prefix = prefix;
  15. buffer = new StringBuilder(128);
  16. this.output = output;
  17. }
  18. /**
  19. * Create a new StreamCapturer without prefix.
  20. *
  21. * @param output Output JTextArea to which this stream should print.
  22. */
  23. public StreamCapturer(JTextArea output) {
  24. this(output, null);
  25. }
  26. @Override
  27. public void write(int b) throws IOException {
  28. char c = (char) b;
  29. String value = Character.toString(c);
  30. buffer.append(value);
  31. if (value.equals("\n")) {
  32. output.append(getPrefix() + buffer.toString());
  33. output.setCaretPosition(output.getText().length());
  34. buffer.delete(0, buffer.length());
  35. }
  36. }
  37. /**
  38. * @return Formatted prefix, or empty string if no prefix is set.
  39. */
  40. public String getPrefix() {
  41. if (this.prefix == null) {
  42. return "";
  43. }
  44. return "[" + prefix + "] ";
  45. }
  46. }