java - Swing 中的 JTextArea 问题

标签 java swing textarea nullpointerexception

我在更新文本区域时遇到问题。

我在gui.java中声明textArea:

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 

最佳答案

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

关于java - Swing 中的 JTextArea 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8981218/

相关文章:

java - JAXRS 客户端找不到消息正文编写器

java - 如何将数组列表项设置为 JButton

java - JTable.updateUI() 不刷新我的表

java - 为什么 .paintComponent() 定义在 JComponent 上?

php - 使用 PHP/jQuery 获取 textarea 的值

java - HTTPUrlConnection 和 .torrent 文件

java - 我应该测试 Spring Boot Application 的 main() 方法吗?如何测试?

javascript - 如何以光标位置为最后一行分割文本区域的值

java - JDBC 连接 URL 中的用户名和密码

css - 我可以设置 textarea 的 resize grabber 样式吗?