Question

How do I create a Swing console window that displays System.out/err while a program is running?

I have an application that uses a lot of System.out status updates that I'd like to migrate out of Eclipse and into a self-contained .jar. I've been attempting to create a "Console Window", which would display System.out and System.err. I used this link as a jump-off point, and while it works fine with the GUI application that the program starts with, as soon as I start the thread that runs the meat of the application, the console window stops updating. I tested redirecting system.out to a file and that worked fine, so I'm confused as to what I might be doing wrong. Essentially, I have a couple main stages of the program.

  1. Program start. Console initializes fine, works until I call the thread.
  2. GUI init. Same.
  3. Initial Logic run. Same.
  4. In the thread where everything seems to stop working: The JTextArea never actually loads - the window is created but the contents are just a copy of whatever was behind the window at the time, and no text is written
Was it helpful?

Solution

I think you are probably trying to update the text area from a thread other than the event dispatching thread, this typically causes the GUI to fail to update / hang / other bad things to happen.

What you want to do is update your display with a call to SwingUtilities.invokeLater (link). Something like this:

SwingUtilities.invokeLater(new Runnable(){
  public void run(){
    myTextArea.append( "Some string" );
  }
});

Rather than using System.out and System.err have you considered using a real logging system? System.out isn't typically used by applications for logging messages because it's an all or nothing approach. With any half way decent logging library you can set levels and fine tune where you receive messages from. Personally I like Logback + SLF4J but the built in logging system in Java is good enough for a simple library.

OTHER TIPS

You can try using the Message Console.

I played with PipedStreams when I was working with the Message Consoles and found them hard to work with so I used a different approach.

In general, you should want to avoid manually logging System.Out stuff as it can get really cumbersome, and implement a logging library such as log4j. This post has some more information on logging libraries.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top