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

标签 java swing variables actionlistener

在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/

相关文章:

java - SpringFox - 隐藏调用端点不需要的 Swagger-ui 中的某些字段

java - 使用 Apache POI 读取 Excel 工作表的列

java - Java拖拽时如何获取鼠标信息?

java - DocumentListener 会减慢 Document.setCharacterAttributes 方法的速度吗?

MySQL 区间变量和子查询符号

string - 读取包含字符串的行(Bash)

java - 设计项目时如何分配作品

java - 接口(interface)作为标签在 Java OO 中是一种不好的做法吗?

java - 是否存在 swing 可过滤 JList 组件?

JavaScript 变量定义 : Commas vs. 分号