Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
677 views
in Technique[技术] by (71.8m points)

user interface - how to display console output in java JTextarea one by one in a loop when button action is triggered

I got a problem with how to display console output in Jtextarea one be one. I have successfully redirected system console output into JTextarea. But the problem is that in real system console, the output show up one by one(i set a Thread.sleep() function, so the result will show up, say, every half seconds). But in JTextarea the output will show only once when the loop finish, it doesn't show one by one like the real system console.

the loop is triggered by a GUI button. please see the sample code below. this is just part of code.

// Create a button.
but.setVerticalTextPosition(AbstractButton.CENTER);
but.setHorizontalTextPosition(AbstractButton.LEADING);
but.setActionCommand("publish");
but.addActionListener(this);

// Button action
public void actionPerformed(ActionEvent e) {
final JButton source = (JButton)e.getSource();
        if(source.equals(but)){
            for( int i = 0 ; i < 5 ; i++ ) {

                System.out.println( i );

                        // regular textarea output
                //JTextarea.append(Integer.toString(i));
                try {
                    Thread.sleep( 500 );
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }

        }
}

as you can see, i use System.out.println( i ) in the loop, because i have redirected system console output into JTextarea, so the output is in JTextarea.

the problem is, like I mentioned above, in real console, the output show one by one every 500 milliseconds. But in redirected Jtextarea, the result shows once when all the loop is done. I don't know why it is like this. I want the output to show one by one as well in redirected JTextarea.

Can anyone please help me. Many thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To make Swing GUI to update dynamically on fire of some event or with some continuous background changes , you can use SwingWorker API provided by Swing. Try this Code :

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DynamicWrite implements ActionListener
{
    JFrame frame = new JFrame("TextArea");
    JTextArea tArea = new JTextArea(10,20);
    JButton button = new JButton("Click");
    JScrollPane pane = new JScrollPane(tArea);
    SwingWorker worker;
    String s= "Java is an Object Oriented Programming langauge...Java is static typed language...asbfldfjsdj";//some random String
    public void prepareAndShowGUI()
    {
        Container container = frame.getContentPane();
        container.add(pane);container.add(button,BorderLayout.NORTH);
        tArea.setLineWrap(true);
        tArea.setWrapStyleWord(true) ;
        button.addActionListener(this);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
    public void actionPerformed(ActionEvent evt)
    {
        if(evt.getSource()==button)
        {
            tArea.setText("");
            if (worker!=null)
            {
                worker.cancel(true);
            }
            worker = new SwingWorker()
            {
                @Override
                protected Integer doInBackground()//Perform the required GUI update here.
                {
                    try
                    {
                        for(int i = 0;i<s.length();i++)
                        {
                            tArea.append(String.valueOf(s.charAt(i)));
                            Thread.sleep(5);
                        }
                    }catch(Exception ex){}
                    return 0;
                }       
            };
            worker.execute();//Schedules this SwingWorker for execution on a worker thread.
        }
    }   
    public static void main(String st[])
    {
        DynamicWrite dyna = new DynamicWrite();
        dyna.prepareAndShowGUI();
    }
}

I hope this solves your problem.
To know more about SwingWorker API watch here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...