62,623
社区成员
发帖
与我相关
我的任务
分享
import java.awt.Point;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.event.MouseInputListener;
public class DragME extends JFrame {
private final JLabel jPic;
public DragME() {
jPic = new JLabel(new ImageIcon(this.getClass().getResource("1.jpg")));
add(jPic);
DragListener listener = new DragListener(this);
jPic.addMouseListener(listener); // 增加标签的事件处理
jPic.addMouseMotionListener(listener);
}
public JLabel getJPic() {
return jPic;
}
public static void main(String args[]) {
DragME drag = new DragME();
drag.setBounds(300, 300, 200, 200);
drag.setVisible(true);
}
}
/*
* DragListener
*/
class DragListener implements MouseInputListener {
private final DragME dragME;
DragListener(DragME d) {
dragME = d;
}
Point p = new Point(0, 0);
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mousePressed(MouseEvent e) {
p = SwingUtilities.convertPoint(dragME.getJPic(), e.getPoint(), dragME
.getJPic().getParent()); // 得到当前坐标点
}
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseDragged(MouseEvent e) {
/*
* convertPoint(Component source, int x, int y, Component destination)将
* source 坐标系统中的点 (x,y) 转换到 destination 坐标系统。
*/
Point newP = SwingUtilities.convertPoint(dragME.getJPic(),
e.getPoint(), dragME.getJPic().getParent()); // 转换坐标系统
dragME.getJPic().setLocation(dragME.getJPic().getX() + (newP.x - p.x),
dragME.getJPic().getY() + (newP.y - p.y)); // 设置标签的新位置
p = newP; // 更改坐标点
}
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}