日期:2014-05-20 浏览次数:20737 次
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
*
* @author Administrator
*/
public class DragTest
{
final Point pointOffset=new Point(0,0);
final JLabel label=new JLabel("123456789");
final int WIDTH=600;
final int HEIGHT=350;
public static void main(String[] args)
{
new DragTest();
}
DragTest()
{
initComponent();
}
void initComponent()
{
JFrame frame=new JFrame();
frame.setSize(WIDTH,HEIGHT);
frame.setLocation(SetCenterFrame.getCenterLocationOfFrame(WIDTH, HEIGHT));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane=frame.getContentPane();
contentPane.add(label);
frame.setVisible(true);
label.addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
pointOffset.x=e.getX();//记录下鼠标按下时鼠标相对于将要拖动组件的x值
pointOffset.y=e.getY();//同上
}
});
label.addMouseMotionListener(new MouseMotionAdapter()
{
public void mouseDragged(MouseEvent e)
{
Component c=e.getComponent();
Point p=e.getPoint();
SwingUtilities.convertPointToScreen(p, c);//将鼠标释放时相对于拖动组件的x,y转换成相对于屏幕的x,y
label.setLocation(p.x-pointOffset.x,
p.y-pointOffset.y); /*拖动组件的位置随鼠标移动,
*具体值等于鼠标相对于屏幕的位置减去鼠标按下时相对于组件的偏移量
*/
}
});
}
}