Getting Program Output into a Window


You want to capture an input/output stream and display it in a text field.


Use an interconnected pair of piped streams and a Thread to read from the input half, and write it to the text area. You may also want to redirect System.out and System.err to the stream; see Section 9.7.


The PipedInputStream and PipedOutputStream provide two streams (see Chapter 9) that are connected together by a buffer and are designed to provide communication between multiple threads (see Section 24.1).

As you’ll see in Chapter 19, I am fairly aggressive in the pursuit of SPAM perpetrators. I have a program called TestOpenMailRelay , derived from the mail sender in Section 19.3, that I use to test whether remote servers are willing to accept mail from unknown third parties and forward it as their own. This gives these bastard messages a parent, just as many birds will glibly nest on a cuckoo’s egg that has been snuck into their nest. This is the GUI for that program; both this and the main program are online in the email directory.

In the constructor, I arrange for the main class to write to the PipedOutputStream; the call to TestOpenMailRelay.process( ) passing the ps argument arranges this. That method will write its own output to the stream in addition to assigning standard output and standard error, so we should see anything it tries to print. To avoid long (possibly infinitely long!) delays, I start an additional thread to read from ...

Get Java Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.