gpt4 book ai didi

Java - Actionlistener 由于我看不到的原因而显示错误

转载 作者:行者123 更新时间:2023-12-02 06:41:48 25 4
gpt4 key购买 nike

在if语句中,未能找到launchBtn。我可能正在做一些愚蠢而明显的事情。谁能看出出了什么问题吗?错误以粗体显示(或用两个 ** 突出显示,这是我的代码:

package launcher;

import java.awt.event.*;

import javax.swing.*;

@SuppressWarnings("serial")
class Window extends JFrame implements ActionListener
{
JPanel panel = new JPanel();

public Window()
{
//Creates the blank panel
super("Launcher");
setSize(500, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(panel);
setVisible(true);

//Create the button variables
JButton launchBtn = new JButton("Launch Game");
JButton optionsBtn = new JButton("Launcher Options");

//Add the buttons to the launcher
panel.add(launchBtn);
panel.add(optionsBtn);

//Add the buttons to the action listener
launchBtn.addActionListener(this);
optionsBtn.addActionListener(this);
}

public void actionPerformed(ActionEvent event)
{
if(event.getSource() == **launchBtn**)
{
**launchBtn**.setEnabled(true);
}
}
}

最佳答案

launchBtn 已在 Window 构造函数的上下文中声明为局部变量。它在构造函数范围之外没有任何意义。

public Window()
{
//...
//Create the button variables
JButton launchBtn = new JButton("Launch Game");

如果您希望访问构造函数之外的变量,您应该创建一个类实例变量...

private JButton launchBtn;
public Window()
{
//...
//Create the button variables
launchBtn = new JButton("Launch Game");

这将允许 Window 类的其他方法引用该变量

关于Java - Actionlistener 由于我看不到的原因而显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19076368/

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