Posted by Rob Camick on November 8, 2008
There may be times when you want to capture output from your program and display it for the user. This is generally done by creating a console. Using Swing it is not too difficult to create a simple console using a JTextArea or JTextPane. Our message console will be able to display output written to System.out and System.err.
The MessageConsole class will enable you to use a text area or text pane as a simple console. First you must decide which component to use:
- JTextArea – will be more efficient
- JTextPane – will allow you to color the text from each source
Next you must decide how you want the console to function:
- append – messages will be added to the bottom of the console
- insert – messages will be inserted as the first line of the console
Finally, you need to decide if you need to limit the number of lines contained in the console. The MessageConsole will use my LimitLinesDocumentListener described in an earlier blog entry.
So the code for a simple useage of this class might be something like:
somePanel.add( new JScrollPane( textComponent ) );
MessageConsole mc = new MessageConsole(textComponent);
One last comment. You can optionally redirect the message to a PrintStream. So if you did something like the following:
The message would display in your message console as well as the normal output console.