在JFrame外拖动JLabel

时间:2012-07-12 16:26:51

标签: java swing drag-and-drop jframe jlabel

所以我一直在看这个:dragging a jlabel around the screen

有没有办法将JLabel(或其中一个代表)拖到JFrame之外?

例如,在JFrame之间拖动JLabel,同时实际“显示”正在拖动的JLabel(使用http://docs.oracle.com/javase/tutorial/uiswing/dnd/intro.html

1 个答案:

答案 0 :(得分:3)

使用JWindow测试:

//http://stackoverflow.com/questions/4893265/dragging-a-jlabel-around-the-screen
private final JWindow window = new JWindow();
@Override
public void mouseDragged(MouseEvent me) {
  if (dragLabel == null) {
      return;
  }
  int x = me.getPoint().x - dragLabelWidthDiv2;
  int y = me.getPoint().y - dragLabelHeightDiv2;
  //dragLabel.setLocation(x, y);
  window.add(dragLabel);
  window.pack();
  Point pt = new Point(x, y);
  Component c = (Component)me.getSource();
  SwingUtilities.convertPointToScreen(pt, c);
  window.setLocation(pt);
  window.setVisible(true);
  repaint();
}
@Override public void mouseReleased(MouseEvent me) {
  window.setVisible(false);
  //...
}

下面没有经过测试的代码: (可能需要一些按摩来工作,但这是它的要点)

@Override public int getSourceActions(JComponent src) {
  JLabel label = (JLabel)src;
  window.add(label);
  window.pack();
  window.setVisible(true);
  return MOVE;
}
//...
DragSource.getDefaultDragSource().addDragSourceMotionListener(new DragSourceMotionListener() {
  @Override public void dragMouseMoved(DragSourceDragEvent dsde) {
    Point pt = dsde.getLocation();
    pt.translate(5, 5); // offset
    window.setLocation(pt);
  }
});