Musings about Java and Swing

Swing Console JDialog

Sometimes, you have some console output that you want to show in a Swing GUI. Last week, I came across an easy way to display console output in a JDialog.

Here’s an example from one of my Java Swing projects.

First, you create a String with your console output. Here’s an example.

	protected String buildCountsMessage(int directoryCount, int sourceCount) {
		StringBuilder builder = new StringBuilder();
		builder.append("JAR file count     : ");
		builder.append(String.format("%,8d", model.getSourceFiles().size()));
		builder.append("JAR directory count: ");
		builder.append(String.format("%,8d", directoryCount));
		builder.append("JAR class count    : ");
		builder.append(String.format("%,8d", sourceCount));

		return builder.toString();

Next, you create a JOptionPane to display the console output. The trick is that you can define any Object to contain the message for the showMessageDialog static method. I chose a JTextArea.

	protected void showMessageDialog(final String s) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				JTextArea message = new JTextArea(s);
				Font font = new Font("Courier New", Font.PLAIN, 12);

				JOptionPane.showMessageDialog(frame.getFrame(), message,
						"Source Code Counts", JOptionPane.INFORMATION_MESSAGE);

The code is inside an invokeLater method because it’s executed outside the Event Dispatch thread (EDT). I set the font to a monospace font so that it still looks like console output. I set the JTextArea component to transparent, so that the background color of the JDialog comes through.

You can add a JScrollPane to hold the JTextArea if you expect a lot of console output. Generally, this is useful for the example I’ve shown; console output to show record counts or other small amounts of console output.


  • Lamont
    Posted Thursday, 12 September 2013 at 11:35 pm | Permalink

    Your means of telling the whole thing in this paragraph is really nice, all be able
    to without difficulty be aware of it, Thanks a lot.

  • Seo consultant Melbourne
    Posted Saturday, 16 November 2013 at 3:14 am | Permalink

    Hey there! Would you mind if I share your blog with my Facebook group? There’s a lot of folks that I think would really enjoy your content. Please let me know.


Post a Comment

Your email is kept private. Required fields are marked *