我已将此侦听器添加到 JLabel 中,并且可以完美地拖动图像,但是,只要单击面板(在不存在 JLabel 的区域中),标签就会返回到其原始位置. 我无法弄清楚为什么会发生这种情况。请帮帮我,我已经花了几个小时来解决这个问题。谢谢!
public class CardLabelListener extends MouseAdapter {
private MouseEvent initiateEvent = null;
@Override
public void mouseReleased(MouseEvent me) {
System.err.println("mouse release");
int dx = me.getX() - initiateEvent.getX();
int dy = me.getY() - initiateEvent.getY();
if (Math.abs(dx) > 5 || Math.abs(dy) > 5) {
Rectangle oldBound = me.getComponent().getBounds();
int newX = oldBound.x + dx;
int newY = oldBound.y + dy;
me.getComponent().setBounds(newX, newY, oldBound.width, oldBound.height);
}
initiateEvent = null;
}
public void mousePressed(MouseEvent me) {
GreetingCard.setBackground.findComponentAt(me.getX(), me.getY());
System.err.println("mouse pressed");
initiateEvent = me;
me.consume();
}
public void mouseDragged(MouseEvent me) {
System.err.println(me.getSource());
if (initiateEvent == null) return;
me.consume();
JComponent jc = (JComponent) me.getSource();
TransferHandler handler = jc.getTransferHandler();
handler.exportAsDrag(jc, me, TransferHandler.MOVE);
initiateEvent = null;
}
}