• category: swing folder: DragSourceMotionListener title: JFrameの外側でもドラッグアイコンを表示する tags: [DragAndDrop, JWindow, ImageIcon, JFrame] author: aterai pubdate: 2012-08-06T15:46:37+09:00 description: ドラッグ中のカーソル位置をDragSourceMotionListenerで取得し、そこにアイコンを追加したWindowを移動することで、JFrameの外側でもドラッグアイコンを表示します。 image: https://lh4.googleusercontent.com/-HM5QzW5AZlk/UB9iFlbSZMI/AAAAAAAABQM/fggojAo0b-E/s800/DragSourceMotionListener.png

概要

ドラッグ中のカーソル位置をDragSourceMotionListenerで取得し、そこにアイコンを追加したWindowを移動することで、JFrameの外側でもドラッグアイコンを表示します。

サンプルコード

final JWindow window = new JWindow();
window.add(label);
//window.setAlwaysOnTop(true);
//com.sun.awt.AWTUtilities.setWindowOpaque(window, false); // JDK 1.6.0
window.setBackground(new Color(0x0, true)); // JDK 1.7.0
DragSource.getDefaultDragSource().addDragSourceMotionListener(new DragSourceMotionListener() {
  @Override public void dragMouseMoved(DragSourceDragEvent dsde) {
    window.setLocation(dsde.getLocation());
  }
});
View in GitHub: Java, Kotlin

解説

上記のサンプルでは、JPanel中に配置したJLabel(アイコン)をDrag & Dropで別のJPanelなど(親のJFrameが異なる場合も可)に移動することができます。ドラッグ中のJLabelは透明化したWindowに配置され、ドラッグに合わせてそのWindowを移動しているので、JFrameの外でもドラッグアイコンが表示可能になっています。 ドラッグ中のカーソル位置取得には、MouseMotionListenerを使用する方法もありますが、このサンプルのようなTransferHandlerを使ったドラッグではMouseMotionListenerでマウスイベントを取得することができないので、DefaultDragSourceDragSourceMotionListenerを追加してドラッグ中のカーソル位置を取得しています。

  • 注:
    • DragSourceDragEvent#getLocation()で取得した位置は、スクリーン座標系なので、そのままWindow#setLocation(...)で使用可能
    • Point pt = tgtLabel.getLocation();で取得したドラッグ対象JLabelの位置は、親コンポーネントの座標系なので、SwingUtilities.convertPointToScreen(pt, parent);で変換する必要がある

参考リンク

コメント