2014-01-17 73 views
0

我的问题

在NetBeans for Java中编译此类。我试图简单地向每个JPanel添加一个ActionListener。然而,当我在代码中键入:为什么我的代码不能识别addActionListener(ActionListener e)方法?

`addActionListener(new SquareMouseListener);` 

我得到的错误:

Cannot Find Symbol; 
    method addActionListener(MinePanel.SquareMouseListener) 
    location: class MinePanel 

下面是完整的代码:

import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.event.*; 
import javax.swing.JPanel; 

public class MinePanel extends JPanel{ 
final private int xPos, yPos; 
final private int numXPanels, numYPanels; 
final private boolean isBomb; 

private MineFrame holderFrame; 
private boolean seen; 

public MinePanel(int xPos, int yPos, int numXPanels, int numYPanels, MineFrame holderFrame) 
{ 
    this.xPos = xPos; 
    this.yPos = yPos; 
    this.numXPanels = numXPanels; 
    this.numYPanels = numYPanels; 
    if(Math.random()<.1) 
    { 
     isBomb = true; 
    } 
    else isBomb = false; 
    seen = false; 

    this.holderFrame = holderFrame; 
    addActionListener(new SquareMouseListener()); 

} 

@Override 
public void paint(Graphics g) 
{ 
    //Color thisColor = new Color((float)Math.random(), (float)Math.random(), (float)Math.random()); 
    g.setColor(Color.BLACK); 
    g.fillRect(0,0,getWidth(),getHeight()); 
    g.setColor(Color.LIGHT_GRAY); 
    g.fillRect(1,1,getWidth()-2,getHeight()-2); 
} 


private class SquareMouseListener implements ActionListener 
{ 
    @Override 
    public void actionPerformed(ActionEvent ae) 
    { 
     System.out.println("Action Performed"); 
    } 
} 
} 

我能做些什么? Netbeans的告诉我导入:

import static com.sun.java.accessibility.util.AWTEventMonitor.addActionListener; 

,但我知道那是不对的,因为我尝试过了,没有工作,因为addActionListener方法应包括的java.awt.event。*;上面的导入。

在此先感谢!

+0

因为MinePanel或JPanel没有定义它 –

回答

2

只需输入this.add并按下ctrl +空格。您将看到可以添加到JPanel的监听器类型。 可能您需要MouseListener。

this.addMouseListener(new YourListener());

其中YourListener实现MouseListener接口。

0

我想出了什么问题,我想发布一个答案,以防其他人在寻找。

试图向JPanel添加ActionListener存在问题,无法完成。 JPanel没有预定义的addActionListener()方法,因为它意味着更低级别的组件。正如@Jigar Joshi所说,JPanel没有定义Action Listener事件。

感谢大家的帮助!

相关问题