【问题标题】:setLocation after window moved窗口移动后的setLocation
【发布时间】:2013-03-05 14:09:07
【问题描述】:

我做了一个拖放算法,让组件被拖到窗口内。

它表现良好,直到我移动框架窗口...

如果我移动窗口,组件的位置会从一个距离移动,该距离等于我单击它和拖动它时移动框架的距离。

有人知道为什么吗?

代码示例:

public void mousePressed(final MouseEvent e) {

    if(SwingUtilities.isLeftMouseButton(e)) {

        origin = panel.getLocationOnScreen();

        panel.setLocation(origin.x, origin.y-panel.getHeight()/2);

        view.add(panel, JLayeredPane.DRAG_LAYER);
    }

}

public void mouseDragged(MouseEvent e) {

   if(SwingUtilities.isLeftMouseButton(e)) {

       panel.setLocation(e.getLocationOnScreen().x - panel.getWidth()/2, e.getLocationOnScreen().y - panel.getHeight()/2);

   }

}

【问题讨论】:

  • 我希望e.getLocationOnScreen() 提供全局坐标,而panel.setLocation(...) 使用相对坐标。但这并不能解释为什么它首先会起作用......
  • @Heuster,你知道如何将 setLocation 转换为全局坐标吗?

标签: java drag-and-drop mouseevent mousemove


【解决方案1】:

假设鼠标事件是由应该在其中拖动面板的容器引发的,您应该只使用相对坐标。

即使用

public void mouseDragged(MouseEvent e) {
   if(SwingUtilities.isLeftMouseButton(e)) {
      panel.setLocation(e.getPoint().x - panel.getWidth()/2, e.getPoint().y - panel.getHeight()/2);
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-06
    • 2020-04-02
    • 2021-11-11
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    相关资源
    最近更新 更多