gpt4 book ai didi

java - 在 ActionListener 中调用 setEnable

转载 作者:行者123 更新时间:2023-12-01 18:33:57 27 4
gpt4 key购买 nike

在我用按钮制作的游戏中,当我单击“下一步”按钮时,我会将其他一些按钮变为“灰色”,以便您无法单击它们。我的 ActionListener 中有以下代码用于“下一步”按钮:

    public class NextListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
nextButton.setEnabled(false);
callButton.setEnabled(false);
raiseButton.setEnabled(false);
}
}

但是,当我运行该程序时,按钮不会变灰,并且出现错误:

    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

为什么这不起作用?

最佳答案

您正在尝试对 null 变量调用方法,因此这表明您调用 setEnabled(...) 的一个或所有 JButton 变量为 null。解决方案:在尝试调用变量的方法之前,为变量分配有效的引用。

这可以通过构造函数参数或类似的参数来完成。或者更好的是,为保存这些按钮变量的类提供一个公共(public)方法,该方法允许您更改其按钮的状态,并将该对象(容器对象)的引用传递给 ActionListener。

例如,

import java.awt.event.ActionListener;
import javax.swing.JButton;

public class MyContainer {
JButton nextButton = new JButton("Next");
JButton callButton = new JButton("Call");
JButton raiseButton = new JButton("Raise");

private ActionListener nextListener = new NextListener(this);

public void buttonsSetEnabled(boolean enabled) {
nextButton.setEnabled(enabled);
callButton.setEnabled(enabled);
raiseButton.setEnabled(enabled);
}
}

其他地方

public class NextListener implements ActionListener {
private MyContainer myContainer;

public NextListener(MyContainer myContainer) {
this.myContainer = myContainer;
}

public void actionPerformed(java.awt.event.ActionEvent e) {
myContainer.buttonsSetEnabled(false);
};
}

关于java - 在 ActionListener 中调用 setEnable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22889227/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com