1.通过对鼠标的监听,更改控件的空间位置
鼠标按下拖拽控件,鼠标松开控件位置改变到当前鼠标位置(拖拽时,控件不可见,松开鼠标时,控件可见),具有一定连续性
jl2.addMouseListener(new MouseListener(){
Point point=new Point(0,0); //创建的控件位置
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
point=SwingUtilities.convertPoint(jl2,e.getPoint(),jl2.getParent());
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
Point newPoint=SwingUtilities.convertPoint(jl2,e.getPoint(),jl2.getParent());
//转换坐标系统
jl2.setLocation(jl2.getX()+(newPoint.x-point.x),jl2.getY()+(newPoint.y-point.y));
//设置标签图片的新位置
point=newPoint; //更改坐标点
int x = jl2.getX();
int y = jl2.getY();
System.out.println(x+","+y);
}
});
2.对鼠标监听直接通过方法setLocatoin或者setBounds改变空间位置
不具有连续性,方法比较简单
jl2.addMouseListener(new MouseListener(){
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
jl2.setLocation(e.getX(),e.getY());//改变控件空间位置
)
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
});
3.通过鼠标监听+线程实时改变控件空间位置,控件跟随鼠标按下时移动(移动过程控件可见)
松开鼠标时线程停止
jl2.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
try {
x = e.getX();
y = e.getY();// 获得鼠标坐标
} catch (Exception a) {
// TODO Auto-generated catch block
}
if (x < x1 + size1 / 2 && y < y1 + 20 + size1 / 2
&& x > x1 - size1 / 2 && y > y1 + 20 - size1 / 2)
k1=true;
if(k1){new Thread(new Runnable() {
public void run() {
while(k1){
try {
x = e.getX();
y = e.getY();// 获得鼠标坐标
} catch (Exception e) {
// TODO Auto-generated catch block
}
x1=x;
y1=y;
jl2.setBounds(-size1 / 2 + x1, -size1 / 2 - 20 + y1, size1, size1);
}
}
}).start();
}
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
int x=0,y=0;
k1=false;
}
});