我正在开发一个 Applet,它有一个 JButton,我想用它来启用另一个 JButton。但是,当我按下按钮时,出现错误:线程“AWT-EventQueue-1”java.lang.NullPointerException 中出现异常。为什么会发生这种情况?似乎当我运行小程序时,全局变量没有被实例化(即它们都是“空”)。在另一个程序中,一切正常,并且我在执行此操作方面找不到两者之间的任何差异。
这是我的一些代码:
public class implementation2 extends Applet implements ActionListener {
private static final long serialVersionUID = -4370650602318597069L;
...
public JButton coreButton, testButton;
...
public void init() {
...
final JButton testButton = new JButton("Test);
testButton.addActionListener(this);
...
final JButton coreButton = new JButton("CORE");
coreButton.addActionListener(this);
coreButton.setEnabled(false);
...
}
...
public void actionPerformed(final ActionEvent event) {
if(event.getActionCommand() == "Test") {
coreButton.setEnabled(false);
}
...
如果有人能指出我修复代码的方向,我将不胜感激!谢谢!
最佳答案
这就是问题:
public JButton coreButton, testButton;
public void init() {
final JButton testButton = new JButton("Test);
在这里,您创建了一个本地变量,它隐藏了 testButton
的实例变量。 (对于 coreButton
也是如此)。这意味着实例变量仍然为空 - 因此当您稍后尝试取消引用它们时,您会收到异常。您不想在 init
中声明新的局部变量- 您只想将值分配给实例变量。更正后的代码:
public class Implementation2 extends Applet implements ActionListener {
private static final long serialVersionUID = -4370650602318597069L;
...
public JButton coreButton, testButton;
...
public void init() {
...
testButton = new JButton("Test");
testButton.addActionListener(this);
...
coreButton = new JButton("CORE");
coreButton.addActionListener(this);
coreButton.setEnabled(false);
...
}
...
public void actionPerformed(final ActionEvent event) {
if("Test".equals(event.getActionCommand())) {
coreButton.setEnabled(false);
}
...
}
}
关于Java Applet 空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5594238/