检查鼠标是否在圆圈内

时间:2013-12-05 10:40:38

标签: java swt

我怎么知道鼠标是否在画布上创建的圆圈内(在swt中) 我的问题是我找到的坐标不正确 这是代码:

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class CircleTest {
    static boolean i =false;
    static int x,y;
  public static void main(String[] args) {
    final Display display = new Display();
    Shell shell = new Shell(display);
    shell.setSize(430, 460);
    final Canvas c=new Canvas(shell,SWT.BORDER);
    c.setSize(370,380);
    c.setLocation(21, 21);

    c.addPaintListener(new PaintListener(){
        public void paintControl(PaintEvent e) {

                x = 50;
                y=50;
                e.gc.drawOval(x, y, 50, 50);
                e.gc.drawRectangle(x, y, 50, 50);
        }

    });  

        c.addMouseMoveListener(new MouseMoveListener(){

            @Override
            public void mouseMove(MouseEvent e) {
                System.out.println(e.x+" "+e.y);
                System.out.println(x+" "+y);

                int k = (e.x-x)*(e.x-x);
                int z = (e.y-y)*(e.y-y);
                double m = Math.sqrt(k + z);
                if (m <=25)
                {
                    System.out.println("in the circle");
                }
            }


        });

    shell.open();
    while(!shell.isDisposed())
    {
        if (!display.readAndDispatch())
            display.sleep();            
    }   
    display.dispose();
  }
 }

有人知道为什么我发现的坐标不好?

1 个答案:

答案 0 :(得分:3)

您的drawOval方法正在指定矩形内绘制圆圈:(x, y, 50, 50)。所以圆圈的中心位于(x + 25, y + 25)。 使用这些坐标可以在mouseMove方法中找到距离中心的距离。