It has some problems though.
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;public class MouseMoveFrame extends JFrame {
   boolean canMove = false;
   int x,y;
   public MouseMoveFrame(){
      setSize(400,300);
      setVisible(true);
      addMouseListener(new MouseAdapter() {
         public void mousePressed(MouseEvent e) {
            canMove = true;
            Point p = getLocation();
            x = p.x - e.getX();
            y = p.y - e.getY();
         }
         public void mouseRelease(MouseEvent e) {
            canMove = false;
         }
      });
      this.addMouseMotionListener(new MouseMotionAdapter() {
         public void mouseDragged(MouseEvent e) {
            setLocation(x+e.getX(),y+e.getY());
         }
      });
   }
   public static void main(String[] args) {
      MouseMoveFrame obj = new MouseMoveFrame();
   }
}

解决方案 »

  1.   

    A sample:import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;public class DragFrame extends JFrame{
    private boolean startDrag = false;
    private Point p = null;
    public static void main(String[] args){
    DragFrame df = new DragFrame();
    df.setSize(400, 400);
    df.setVisible(true);
    }
    public DragFrame(){
    addMouseListener(new MouseAdapter(){
    public void mousePressed(MouseEvent e){
    startDrag = true;
    p = e.getPoint();
    }
    public void mouseReleased(MouseEvent e){
    startDrag = false;
    }
    });
    addMouseMotionListener(new MouseMotionAdapter(){
    public void mouseDragged(MouseEvent e){
    Point p1 = e.getPoint();
    Point p2 = getLocation(null);
    p2.x += p1.x - p.x;
    p2.y += p1.y - p.y;
    setLocation(p2);
    }
    });
    }
    }
      

  2.   

    helpall(),你的代码实现有抖动啊。
      

  3.   

    juhwali(华仔)的算法好. 我说了我的程序是有问题的,只是大意.