日期:2014-05-20  浏览次数:20699 次

鼠标监控事件小问题
[code=Java][/code]/*
 * 让兔子随鼠标的移动而动
 */
package zhouyong3;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test1_4 extends JFrame{

MyPanel mp2=null;
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Test1_4 test1_4=new Test1_4();
}

public Test1_4()
{
mp2=new MyPanel();

this.add(mp2);
this.addMouseListener(mp2);

this.setAlwaysOnTop(true);
this.setVisible(true);
this.setSize(400,600);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}

}

class MyPanel extends JPanel implements MouseListener
{
int x=90;
int y=90;

public void paint(Graphics g)
{
super.paint(g);

// Image img=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/coney.png"));
// g.drawImage(img, x, y, 117, 117, this);

}

public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
System.out.print("鼠标点击了"+" ");
}

public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
System.out.print("鼠标进来了"+" ");
}

public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
System.out.print("鼠标退出了"+" ");
}

public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
System.out.print("鼠标按下了"+" ");
}

public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub

}
}
最后老报错:如下:
Exception in thread "main" java.lang.ClassCastException: zhouyong3.MyPanel
at java.awt.AWTEventMulticaster.add(Unknown Source)
at java.awt.Component.addMouseListener(Unknown Source)
at zhouyong3.Test1_4.<init>(Test1_4.java:22)
at zhouyong3.Test1_4.main(Test1_4.java:14)
请大侠指点一下,找了半天了.....

------解决方案--------------------
探讨

唉,解决了,原来是这个包下面已经定义过了一个MyPanel 类