O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Getting Program Output into a Window

Problem

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

Solution

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.

Discussion

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required