SwingUtilities类是Swing组件内部使用的实用工具,它提供了许多的涉及计算、转换、访问控制、布局等方面的方法。这里我们只讨论它的一个方法public static Point convertPoint(Component source,Point aPoint,Component destination) ;要想理解这个方法,利用图形的方式是最好不过了。如下图:
[img]http://www.kutoku.info/images/java/100817/SwingUtilities.png[/img]
我们假设最大的容器Container为destination,显示图像的JLabel为source,我们给source增加鼠标监听事件,那么aPoint是指鼠标在source的位置。当我们点击图片上箭头指的位置,aPoint的x值和y值都为0,Pont destPoint = SwingUtilities.convertPoint(Component source,Point aPoint,Component destination) ;destPoint的x值和y值分别是:39 和 86。
我们再用程序来解释这个方法。我们给Component source增加鼠标监听方法,当有鼠标点击source的左上角(上图箭头所指位置)时,触发public void mousePressed(MouseEvent event)方法,我们通过event拿到aPoint,然后我们就可以拿到aPoint的x(event.getPoint().x)和y(event.getPoint().y)值,根据上图他们分别是0,0;而destPoint的值,则是39,86
[code]
public void mousePressed(MouseEvent event) {
// 得到当前坐标点
destPoint = SwingUtilities.convertPoint(dragPicLabel, event.getPoint(),
dragPicLabel.getParent());
// 点击source的左上角(图片上箭头指向),输出 0:0
System.out.println(event.getPoint().x + " : " + event.getPoint().y);
// 点击source的左上角(图片上箭头指向),输出 39 : 86
System.out.println(destPoint.x + " : " + destPoint.y);
}
[/code]
现在明白了吧,[b]SwingUtilities.convertPoint(Component source,Point aPoint,Component destination) 的目的就是将坐标系的原点从source转移到destination。根据原来的鼠标位置aPoint,获得坐标转以后的鼠标位置destPoint[/b]。这个方法在获得鼠标移动距离,画坐标系,划线时会经常用到。
文章地址:[url]http://javapub.iteye.com/blog/739146[/url]
[img]http://www.kutoku.info/images/java/100817/SwingUtilities.png[/img]
我们假设最大的容器Container为destination,显示图像的JLabel为source,我们给source增加鼠标监听事件,那么aPoint是指鼠标在source的位置。当我们点击图片上箭头指的位置,aPoint的x值和y值都为0,Pont destPoint = SwingUtilities.convertPoint(Component source,Point aPoint,Component destination) ;destPoint的x值和y值分别是:39 和 86。
我们再用程序来解释这个方法。我们给Component source增加鼠标监听方法,当有鼠标点击source的左上角(上图箭头所指位置)时,触发public void mousePressed(MouseEvent event)方法,我们通过event拿到aPoint,然后我们就可以拿到aPoint的x(event.getPoint().x)和y(event.getPoint().y)值,根据上图他们分别是0,0;而destPoint的值,则是39,86
[code]
public void mousePressed(MouseEvent event) {
// 得到当前坐标点
destPoint = SwingUtilities.convertPoint(dragPicLabel, event.getPoint(),
dragPicLabel.getParent());
// 点击source的左上角(图片上箭头指向),输出 0:0
System.out.println(event.getPoint().x + " : " + event.getPoint().y);
// 点击source的左上角(图片上箭头指向),输出 39 : 86
System.out.println(destPoint.x + " : " + destPoint.y);
}
[/code]
现在明白了吧,[b]SwingUtilities.convertPoint(Component source,Point aPoint,Component destination) 的目的就是将坐标系的原点从source转移到destination。根据原来的鼠标位置aPoint,获得坐标转以后的鼠标位置destPoint[/b]。这个方法在获得鼠标移动距离,画坐标系,划线时会经常用到。
文章地址:[url]http://javapub.iteye.com/blog/739146[/url]