【问题标题】:Gap between mouse on screen and JPanel on Dragndrop屏幕上的鼠标和 Dragndrop 上的 JPanel 之间的间隙
【发布时间】:2014-11-23 02:56:55
【问题描述】:

我使用 JPanel 在屏幕上绘制一个正方形。 当我使用 MouseDragged 时,它工作正常,几乎可以去任何我想去的地方。每次我点击方块时,方块会自动移动,左上角在鼠标正下方。 我应该怎么做才能使正方形不会自行替换并保持在鼠标下方? 感谢您的帮助。

【问题讨论】:

    标签: java user-interface jpanel


    【解决方案1】:

    记下你所在组件的top-left坐标之间的差异 移动和mousePressed 位置。
    当您获得新职位时,只需减去该差异即可。
    在这里,我试图通过编码来解释它。让myJPanel 成为你想要的组件 移动。那么这里是可以为您工作的MouseAdapter。新位置存储在 newPosition 变量。

    new MouseAdapter(){
        int diffx = 0, diffy = 0;
        public void mousePressed(MouseEvent e) {
            Point topLeft = myJPanel.getLocation();
            Point mouseDn = e.getPoint();
            diffx = mouseDn.x - topLeft.x;
            diffy = mouseDn.y - topLeft.y;
        }
    
        public void mouseDragged(MouseEvent e) {
            Point mouseDr = e.getPoint();
            int newX = mouseDr.x - diffx;
            int newY = mouseDr.y - diffy;
            Point newPosition = new Point(newX, newY);
        }
    };
    

    【讨论】:

      猜你喜欢
      • 2018-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-31
      • 2020-05-27
      相关资源
      最近更新 更多