我正在创建我的第一个 GUI,但遇到了一个我似乎无法克服的问题。通过按下按钮执行方法后,我想将 JTextArea 设置为“”或 null。在按下按钮的那一刻,一个方法执行并且程序正常运行但 TextArea 不为空。我在这段代码中得到了一个“java.lang.NullPointerException”:
JButton JInputFile = new JButton("Input network file");
JInputFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
final JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
String fileName = file.getName();
network = new Network(fileName);
JTextAreaResult.append(null); //exception points to this line
}
}
});
JInputFile.setFont(new Font("Calibri", Font.PLAIN, 11));
JInputFile.setBounds(20, 56, 294, 20);
contentPane.add(JInputFile);
我可能没有提供足够的信息,所以让我知道。什么可能会阻止我的 JTextArea 清空,我该如何解决?
最佳答案
- 首先,它不是
.append(null);
,而是.setText("");
。 - 另一方面,您的 JTextAreaResult 变量在您尝试使用它的范围内是否为 null?
- 第三,您的变量名应该符合 Java 命名标准,并且应该以小写字母开头。这有助于其他人(我们!)更好地阅读和理解您的代码。
- 此外,您似乎在使用空布局并在组件上调用
setBounds(...)
。虽然这对新手来说似乎是创建复杂 GUI 的更好方法,但这是一个谬论,您创建 Swing GUI 的次数越多,您就越学会尊重和使用布局管理器,并且看到这些生物极大地帮助创建灵活、美观且如果需要复杂的 GUI。
关于Java Swing : Setting a JTextArea to Null After Method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21418396/