【问题标题】:Dragging a JLabel outside of a JFrame将 JLabel 拖到 JFrame 之外
【发布时间】:2012-07-12 16:26:51
【问题描述】:

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

有没有办法将 JLabel(或其中的表示)拖到 JFrame 之外?

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

【问题讨论】:

  • 你没有回答你自己的问题吗?
  • 我是如何回答自己的问题的?

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


【解决方案1】:

使用 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);
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多