Why is my thread not working properly in Swing?

Viewed 443

I am printing simple value to append JTextArea using simple for loop, and when I run it, it's properly Run if I print value in console output...

But if I append JTextArea and print value in the text area, they are appended all after whole program run.

public class SwingThread {

private JFrame frame;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                SwingThread window = new SwingThread();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public SwingThread() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JScrollPane scrollPane = new JScrollPane();
    frame.getContentPane().add(scrollPane, BorderLayout.CENTER);

    JTextArea textArea = new JTextArea();
    scrollPane.setViewportView(textArea);

    JButton btnNewButton = new JButton("New button");
    scrollPane.setColumnHeaderView(btnNewButton);
    btnNewButton.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent arg0)
        {
            try
            {
                for(int i = 0 ; i <= 5 ; i++)
                {
                    textArea.append("Value "+i+"\n");
                    System.out.println("Value is" + i);
                    Thread.sleep(1000);
                }
            }
            catch(Exception e)
            {
                System.out.println("Error : "+e);
            }
        }
    });
}
}

I want to append one by one, but it was appended after the whole program runs.

1 Answers
Related