2013-09-29 53 views
0

在if语句中,找不到launchBtn。我可能做了一些愚蠢的事情。任何人都可以看到有什么不对?这些错误是大胆的(或有两个**,这里是我的代码高亮显示:Java - Actionlistener显示错误的原因我看不到

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); 
    } 
} 
} 

回答

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

1

你可能想launchBtnoptionsBtn是这个类,在构造函数中声明不是局部变量的实例变量将其申报给构造之外。

+0

我知道这将是愚蠢的!谢谢。 –