Amit
Amit

Reputation: 34735

Problem with Java GUI

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.

Upvotes: 0

Views: 308

Answers (3)

tangens
tangens

Reputation: 39733

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);

Upvotes: 5

John Kugelman
John Kugelman

Reputation: 361605

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.

Upvotes: 1

torbjoernwh
torbjoernwh

Reputation: 445

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.

Upvotes: 1

Related Questions