Swing中JTextArea的问题

时间:2012-01-24 02:02:59

标签: java swing textarea nullpointerexception

我无法更新文字区域。

我在textArea声明gui.java

JTextArea textArea;

我启动了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);
    }

我有一个写入上面textArea的方法:

public void writeToTextArea(String userInputText) {
        textArea.append("\nSYSTEM: "
                + userInputText);
    }

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

gui.writeToTextArea("PROGRAM STARTED!");

我的问题是文本区域字段没有更新。什么都没有输入。我认为这是因为找不到textArea是什么。我得到了:

Exception in thread "main" java.lang.NullPointerException 

1 个答案:

答案 0 :(得分:6)

您在textArea函数中声明了另一个名为startGUI的变量,该变量隐藏了类级别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
}