[英]Issue with JTextArea in Swing
我在更新文本区域时遇到问题。
我宣布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
您在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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.