Java - Actionlistener因我无法看到的原因显示错误

时间:2013-09-29 09:21:05

标签: 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);
    }
}
}

2 个答案:

答案 0 :(得分:1)

您可能希望launchBtnoptionsBtn成为此类的实例变量,而不是构造函数中声明的局部变量。将它们的声明移到构造函数之外。

答案 1 :(得分:1)

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类的其他方法引用变量