Swing中JTextArea的问题

dro*_*dus 0 java swing textarea nullpointerexception

我无法更新文本区域.

我宣布textAreagui.java:

JTextArea textArea;
Run Code Online (Sandbox Code Playgroud)

我启动了GUI ..

public void startGUI() {
        // These are all essential GUI pieces
        JLabel jLabInstruction, jLaberror;
        JLabel copyright = new JLabel("");
        JTextField uI = new JTextField("");
        JTextArea textArea = new JTextArea("");
        JButton jbtnSubmit;

        final JFrame jfrm = new JFrame("app name!");
        jfrm.setLayout(new FlowLayout());
        jfrm.setSize(300, 300);
        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        textArea = new JTextArea(5, 20);
        textArea.setEditable(false);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        jLabInstruction = new JLabel("SYSTEM: Please type in a command: ");
        jbtnSubmit = new JButton("Submit");
        jLaberror = new JLabel("");
        textArea.setMargin(new Insets(10,10,10,10));

        jfrm.add(jLaberror);
        jfrm.add(textArea);
        jfrm.add(jLabInstruction);
        jfrm.add(uI);
        jfrm.add(jbtnSubmit);
        jfrm.add(new JSeparator(SwingConstants.HORIZONTAL));
        jfrm.add(copyright);
        jfrm.setVisible(true);
    }
Run Code Online (Sandbox Code Playgroud)

我有一个方法写到textArea上面:

public void writeToTextArea(String userInputText) {
        textArea.append("\nSYSTEM: "
                + userInputText);
    }
Run Code Online (Sandbox Code Playgroud)

另外,tasks.java我可以调用最后一种方法:

gui.writeToTextArea("PROGRAM STARTED!");
Run Code Online (Sandbox Code Playgroud)

我的问题是文本区域字段没有更新.什么都没有输入.我在想它是因为找不到它是什么textArea.我得到一个:

Exception in thread "main" java.lang.NullPointerException 
Run Code Online (Sandbox Code Playgroud)

Per*_*ion 6

您正在声明textAreastartGUI函数中调用的另一个变量,它隐藏了类级别textArea.这就是为什么当您尝试在程序中稍后写入文本区域时获得NPE的原因.

JTextArea textArea;

public void startGUI() {
    JLabel jLabInstruction, jLaberror;
    JLabel copyright = new JLabel("");
    JTextField uI = new JTextField("");
    JTextArea textArea = new JTextArea(""); //<-- Your hiding your class variable here

    // ... rest of your code
}
Run Code Online (Sandbox Code Playgroud)