---
title: "几行代码搞定Java桌面应用程序界面的拖动问题"
author: "forchase"
date: "2010-12-22T11:36:43Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2010-12-22T11:39:19Z"
id: 849138
url: "https://forchase.iteye.com/blog/849138"
---

有时我们想让鼠标点击Java桌面应用程序界面的任何地方都能实现拖动功能,而不止限于标题栏,下面几行代码就能实现之,其实很简单,只需将当前界面的坐标加上鼠标移动的距离即可.

 

     首先写一个类,继承MouseListener, MouseMotionListener,其他方法体里面不需要写代码,只需在mousePressed()和mouseDragged()方法里写些代码即可(省略了部分代码):

 

```
	int startX ,startY;
 
 	Component c;	
	
	public DraggingListener(Component c) {
 		this.c = c;
 	}
	
	public void mousePressed(MouseEvent e) {
		startX = e.getX();//开始移动时界面左上角X坐标
		startY = e.getY();//开始移动时界面左上角Y坐标
	}
	public void mouseDragged(MouseEvent e) {
		Point p = e.getPoint();
		int addX = p.x - startX;//X轴上移动的距离
		int addY = p.y - startY;//X轴上移动的距离
		Point old = c.getLocation();
		c.setLocation(old.x + addX, old.y + addY);
	}
```

 

然后为你的主框架注册事件监听器:

 

 

```
DraggingListener listener = new DraggingListener(this);
this.addMouseListener(listener);
this.addMouseMotionListener(listener);
```

 

 

OVER!!