[英]Java Applet NullPointerException
我正在开发一个Applet,它有一个我想用来启用另一个JButton的JButton。 但是,当我按下按钮时,我收到错误:线程“AWT-EventQueue-1”中的异常java.lang.NullPointerException。 为什么会这样? 好像当我运行Applet时,全局变量不会被实例化(即它们都是“null”)。 在另一个程序中,一切正常,我在实现此操作方面找不到两者之间的任何差异。
这是我的一些代码:
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);
}
...
}
}
当你将它们声明为全局时,为什么再次在init()
中的init()中声明它们只是写:
public void init() {
...
testButton = new JButton("Test");
testButton.addActionListener(this);
...
coreButton = new JButton("CORE");
coreButton.addActionListener(this);
coreButton.setEnabled(false);
...
}
代码中可能存在的错误:
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); //---- Duplicate declaration which should not be done.
//---- Forgot to write `"` to finish `Test` string
testButton.addActionListener(this);
...
final JButton coreButton = new JButton("CORE"); //---- Duplicate declaration which should not be done.
coreButton.addActionListener(this);
coreButton.setEnabled(false);
...
}
...
public void actionPerformed(final ActionEvent event) {
if(event.getActionCommand() == "Test") { //--- use `.equals()` instead of `==`
coreButton.setEnabled(false); //---- set it to `true` instead of `false`.
}
在init()中,你创建了两个隐藏外部按钮的本地按钮,因此,它们在init()之后仍然为null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.