java程序MouseAdapter类中使用疑问?

来源:百度知道 编辑:UC知道 时间:2024/05/12 15:09:43
/*引入图形包、事件响应包、集合类包*/
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class MyMouseAdapter2 {
public static void main(String[] args) {
new MyFrame("draw the point");//实现窗体
}
}
/*定义一个窗体类*/
class MyFrame extends Frame {
HashSet points = new HashSet();//定义一个集合对象,以便放置窗体组件上画出的每个点对象
MyFrame(String s) {
super(s);
setLayout(null);
setBounds(100,100,200,200);
setBackground(new Color(215,255,203));
setVisible(true);
addMouseListener(new MouseMonitor());//添加个鼠标监听在此窗体上
}
/*添加每个在窗体上画出的点对象到集合类*/
public void addPoint(Point t) {
points.add(t);
}
/*重集合中把每个画在窗体上的点对象实现出来---画到图形上*/
public void paint(Graphics g) {
Color cl = g.getColor();
g.setColor(Color.red);//把颜色设置为红
Iterator itr = points.iterator();//为遍历准备
/*把集合类中所有对象实现出来*/
while(itr.hasNext()) {
Point tt = (Point)itr.next(

使用MouseMotionAdapter的mouseDragged方法,不要使用MouseAdapter的这个方法。
在sun的帮助文档上MouseAdapter的mouseDragged方法说明中有这么一句话,不知道你注意了没有:

Due to platform-dependent Drag&Drop implementations, MOUSE_DRAGGED events may not be delivered during a native Drag&Drop operation.

就是说这里的这个方法是基于平台实现的,在拖动过程中拖动事件可能不被传递(也就是这个方法可能不会被调用)。
而MouseMotionAdapter中的mouseDragged方法并没有这句话。事实也证明MouseMotionAdapter中的这个方法总是能够被调用