1 package org.opentrafficsim.remotecontrol;
2
3 import java.io.OutputStream;
4 import java.lang.reflect.InvocationTargetException;
5
6 import javax.swing.JTextArea;
7 import javax.swing.SwingUtilities;
8
9
10
11
12
13
14
15
16
17
18
19
20 public class TextAreaOutputStream extends OutputStream
21 {
22
23 private final JTextArea textArea;
24
25
26
27
28
29 TextAreaOutputStream(final JTextArea textArea)
30 {
31 this.textArea = textArea;
32 }
33
34
35
36
37
38
39
40 public void awtWrite(final byte[] bytes, final int offset, final int length)
41 {
42 synchronized (this.textArea)
43 {
44 for (int index = offset; index < offset + length; index++)
45 {
46
47 this.textArea.append(String.valueOf((char) (bytes[index])));
48 }
49
50 this.textArea.setCaretPosition(this.textArea.getDocument().getLength());
51 }
52 }
53
54
55
56
57
58 public void awtWrite(final int b)
59 {
60 synchronized (this.textArea)
61 {
62
63 this.textArea.append(String.valueOf((char) b));
64
65 this.textArea.setCaretPosition(this.textArea.getDocument().getLength());
66 }
67 }
68
69
70 @Override
71 public void write(final byte[] bytes, final int offset, final int length)
72 {
73 if (SwingUtilities.isEventDispatchThread())
74 {
75 awtWrite(bytes, offset, length);
76 }
77 else
78 {
79 try
80 {
81 SwingUtilities.invokeAndWait(new Runnable()
82 {
83
84 @Override
85 public void run()
86 {
87 awtWrite(bytes, offset, length);
88 }
89 });
90 }
91 catch (InvocationTargetException | InterruptedException e)
92 {
93 e.printStackTrace();
94 }
95 }
96 }
97
98
99 @Override
100 public void write(final byte[] bytes)
101 {
102 write(bytes, 0, bytes.length);
103 }
104
105
106 @Override
107 public void write(final int b)
108 {
109 try
110 {
111 SwingUtilities.invokeAndWait(new Runnable()
112 {
113
114 @Override
115 public void run()
116 {
117 awtWrite(b);
118 }
119 });
120 }
121 catch (InvocationTargetException | InterruptedException e)
122 {
123 e.printStackTrace();
124 }
125 }
126
127 }