0

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.

2
  • I don't believe there's any way to change where System.out.println() goes, so if you're trying to do that you're probably out of luck. This is where logging frameworks like log4j come in handy, as you can configure where the log messages go. Commented Oct 13, 2009 at 19:38
  • @Herms: java.sun.com/javase/6/docs/api/java/lang/… Commented Oct 13, 2009 at 19:43

3 Answers 3

5

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Added SwingUtilities.invokeLater().
@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.
Actually, that might not also be the case for setCaretPosition (I'm not sure), so it may still be necessary.
1

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.

1 Comment

Technically, yes, you can use a JLabel, but why would you use a JLabel for something other than labelling something?
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.