2

So I've been looking at this: dragging a jlabel around the screen

Is there a way to drag a JLabel (or a representation of one) outside of a JFrame?

For instance to drag a JLabel between JFrames, while actually "showing" the JLabel being dragged (using http://docs.oracle.com/javase/tutorial/uiswing/dnd/intro.html)

Community
  • 1
  • 1
mainstringargs
  • 13,563
  • 35
  • 109
  • 174

1 Answers1

3

Using JWindow test:

//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);
  //...
}

Below is not tested code: (may take some massaging to work, but this is the gist of it)

@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);
  }
});
aterai
  • 9,658
  • 4
  • 35
  • 44