【问题标题】:Issue with JTextArea in SwingSwing 中的 JTextArea 问题
【发布时间】:2012-01-24 02:02:59
【问题描述】:

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

我在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 

【问题讨论】:

  • 如需尽快获得更好的帮助,请发帖SSCCE

标签: java swing textarea nullpointerexception


【解决方案1】:

您在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
}

【讨论】:

  • 我尝试将这一行注释掉,但似乎不起作用。
  • 不要注释掉这一行。只需停止重新声明变量。又名textArea = new JTextArea("");.
  • +1。 @droidus,您不能注释掉该行,因为您需要创建文本区域。
  • 我收到更多错误:userInput.askGetInput("创建文件时出错。您要继续进行诊断吗?(键入 \"y\" 或 \"yes\",或\"n\" 或 \"no\".) 这将只需要一分钟。"); (taskBckg.java),以及这里... // 写入文本区域 public void writeToTextArea(String userInputText) { textArea.append("\nSYSTEM: " + userInputText); } // 询问用户输入 public void askGetInput(String outText) { writeToTextArea(outText); }
  • 我仍然收到“java.lang.NullPointerException”错误,不知道为什么。只有在添加这 3 个语句后才会发生...
猜你喜欢
  • 2011-05-29
  • 1970-01-01
  • 2017-07-30
  • 2021-12-03
  • 2013-10-22
  • 1970-01-01
相关资源
最近更新 更多