代码之家  ›  专栏  ›  技术社区  ›  Asher

在GUI中使用拖放时的精确定位

  •  0
  • Asher  · 技术社区  · 10 年前

    我正在尝试为我使用WindowBuilder/SWT Designer创建的GUI实现拖放功能。目前,为了确定放置在画布上的确切位置,我使用

    canvas.addPaintListener(new PaintListener() {
        public void paintControl(PaintEvent e) {
            int x = event.x - shell.getBounds().x - canvas.getBounds().x;
            int y = event.y - shell.getBounds().y - canvas.getBounds().y;
            e.gc.drawString(d, x, y);
        }
    });
    

    但这并不是鼠标落下时的准确位置,相反,它更靠近右侧。我怎样才能解决这个问题?谢谢

    1 回复  |  直到 10 年前
        1
  •  0
  •   Baz    10 年前

    你所需要的是非常有用的功能 Control#toControl(int, int) :

    返回一个点,该点是将显示相对坐标中指定的参数转换为相对于接收器的坐标的结果。

    canvas.addPaintListener(new PaintListener()
    {
        public void paintControl(PaintEvent e)
        {
            Point point = canvas.toControl(event.x, event.y);
            e.gc.drawString(d, point.x, point.y);
        }
    });
    

    那就行了。