无法从另一个线程更新JTextArea

时间:2017-03-18 01:58:32

标签: java swing awt invocation eventqueue

我不确定我在下面的代码中出错了什么。它不允许我从extraThread更新JTextArea。我可以看到控制台窗口中的状态值已更新,但它对JTextArea不起作用。

错误

java.lang.NullPointerException
    at test.UI$4.run(UI.java:77)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)

代码

package test;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class UI {

    private JFrame frame;
    private JTextArea txtArea;

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

    public UI() {
        initialize();
    }

    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 171, 334);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JTextArea textArea = new JTextArea();
        textArea.setBounds(10, 11, 133, 239);
        frame.getContentPane().add(textArea);

        JButton btnStart = new JButton("Start");
        btnStart.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                process();
            }
        });
        btnStart.setBounds(10, 261, 133, 23);
        frame.getContentPane().add(btnStart);
    }

    private void process() {
        Thread extraThread = new Thread(new Runnable() {
            public void run() {
                int i = 0;
                for(;;) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    String status = "Cnt " + i;
                    System.out.println(status);
                    updateTextArea(status);
                    i++;
                }
            }
        });
        extraThread.start();
    }

    private void updateTextArea(String i) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                String prev = txtArea.getText();
                txtArea.setText(prev + "\n" + i);   
            }
        });
    }
}

0 个答案:

没有答案