tags:

views:

68

answers:

3

I have made a java program with GUI. Now I want to add a component on the GUI where I can display whatever I want in the same way we display output through

System.out.println();

Which component I can add on the GUI and how to display content on that component.

+5  A: 

You could define a PrintStream that prints to a JTextArea:

    final JTextArea textArea = new JTextArea();
    PrintStream printStream = new PrintStream( new OutputStream() {
        @Override
        public void write( final int b ) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    textArea.append( "" + (char )b );
                    textArea.setCaretPosition( textArea.getText().length() );
                }
            });
        }
    } );
    System.setOut(printStream);
tangens
Added `SwingUtilities.invokeLater()`.
John Kugelman
Added `System.setOut()`.
Michael Myers
Thanks to @John. I'll use this in my code, too.
tangens
@John: invokeLater is not necessary in this particular case because JTextArea.append is one of the few Swing methods that is safe to call from any thread.
Dan Dyer
Actually, that might not also be the case for setCaretPosition (I'm not sure), so it may still be necessary.
Dan Dyer
+1  A: 

For just one line you can use a JLabel and set its text property. How to use JLabel: http://www.leepoint.net/notes-java/GUI/components/10labels/jlabel.html

Or if you need to print multiple lines you can use a JTextArea-box.

Its also possible to draw/paint text ontop of the GUI-panel with Java2D and the Graphics object.

torbjoernwh
Technically, yes, you can use a JLabel, but why would you use a JLabel for something other than labelling something?
Thomas Owens
+1  A: 

You can use a JTextArea and add text to it each time you print something. Call setEditable(false) so it's read-only. Add it to a JScrollPane so it's scrollable.

Or you could use a JList and add each line as a separate list item. It won't do word wrapping but if you're displaying something akin to an event log it'll look good for that purpose.

John Kugelman