0

我不确定我在下面的代码中做错了什么。它不允许我从 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);   
            }
        });
    }
}
4

0 回答 0