package EventPac;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class MouseAdapter extends JFrame {
private JLabel lblN;
private JLabel lblS;
public MouseAdapter() {
super("鼠标事件测试");
Container c = this.getContentPane();
c.setLayout(new BorderLayout());
lblN = new JLabel("请移动鼠标");
lblS = new JLabel("请拖动鼠标");
c.add(lblN, BorderLayout.NORTH);
c.add(lblS, BorderLayout.SOUTH);
// 将当前窗体注册到MouseMotionListener监听器
this.addMouseMotionListener(new NewMouseMotionListener());
// 将当前窗体注册到MouseListener监听器
[b] this.addMouseListener(new MyMouseListener());
[/b] this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(300, 300);
this.setVisible(true);
}
private class NewMouseMotionListener extends MouseMotionAdapter {
// 内部类实现MouseMotionListener监听器接口,代码略
public void mouseDragged(MouseEvent e) {
lblS.setText("你正在拖动鼠标" + e.getX() + "," + e.getY());
}
public void mouseMoved(MouseEvent e) {
lblN.setText("你正在移动鼠标" + e.getX() + "," + e.getY());
}
}
private class MyMouseListener extends MouseAdapter {
// 只需要重写鼠标离开时的事件处理函数
public void mouseExited(MouseEvent me) {
lblN.setText("鼠标已经离开窗体");
lblS.setText("鼠标已经离开窗体");
}
}
}
public class MouseAdapterTest {
public static void main(String[] args) {
new MouseAdapter();
}
}
红色那行处问题报错如下:
类型 Component 中的方法 addMouseListener(MouseListener)对于参数(MouseAdapter.MyMouseListener)不适用
上面那行调用MouseMotionAdapter的就没有问题啊。。。。。
急死了,一晚上也没搞明白~~
------解决方案--------------------
...........
错误1:MyMouseListener 继承 MouseAdapter
然后你又在MouseAdapter的构造函数中new了一个MouseAdapter
错误2:this.addMouseListener()//你至少应该传入一个实现了java.awt.MouseListener接口的类
MyMouseListener只继承了一个JFrame的类