Swing/DragSourceMotionListener のバックアップ(No.7)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- Swing/DragSourceMotionListener へ行く。
- 1 (2012-08-06 (月) 15:46:37)
- 2 (2012-08-07 (火) 11:04:46)
- 3 (2012-08-07 (火) 14:19:12)
- 4 (2012-11-17 (土) 03:46:38)
- 5 (2012-12-07 (金) 18:13:23)
- 6 (2013-01-29 (火) 23:42:26)
- 7 (2013-10-25 (金) 18:04:11)
- 8 (2013-10-29 (火) 15:37:15)
- 9 (2013-10-30 (水) 21:20:06)
- 10 (2014-11-01 (土) 00:46:09)
- 11 (2015-04-02 (木) 15:10:43)
- 12 (2017-02-28 (火) 13:07:16)
- 13 (2017-11-02 (木) 15:34:40)
- 14 (2018-01-04 (木) 12:29:03)
- 15 (2018-09-27 (木) 20:48:31)
- 16 (2020-09-29 (火) 18:32:53)
- 17 (2022-06-01 (水) 16:53:24)
- 18 (2022-08-20 (土) 22:15:25)
- 19 (2025-01-03 (金) 08:57:02)
- 20 (2025-01-03 (金) 09:01:23)
- 21 (2025-01-03 (金) 09:02:38)
- 22 (2025-01-03 (金) 09:03:21)
- 23 (2025-01-03 (金) 09:04:02)
- 24 (2025-06-19 (木) 12:41:37)
- 25 (2025-06-19 (木) 12:43:47)
TITLE:JFrameの外側でもドラッグアイコンを表示する
Posted by aterai at 2012-08-06
JFrameの外側でもドラッグアイコンを表示する
ドラッグ中のカーソル位置をDragSourceMotionListener
で取得し、そこにアイコンを追加したWindow
を移動することで、JFrame
の外側でもドラッグアイコンを表示します。
- &jnlp;
- &jar;
- &zip;
サンプルコード
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(0, true)); // JDK 1.7.0
DragSource.getDefaultDragSource().addDragSourceMotionListener(new DragSourceMotionListener() {
@Override public void dragMouseMoved(DragSourceDragEvent dsde) {
window.setLocation(dsde.getLocation());
window.setVisible(true);
}
});
View in GitHub: Java, Kotlin解説
上記のサンプルでは、JPanel
中に配置したJLabel
(アイコン)をDrag & Drop
で別のJPanel
など(親のJFrame
が異なる場合も可)に移動することができます。ドラッグ中のJLabel
は透明化したWindow
に配置され、ドラッグに合わせてそのWindow
を移動しているので、JFrame
の外でもドラッグアイコンが表示可能になっています。
ドラッグ中のカーソル位置取得には、MouseMotionListener
を使用する方法もありますが、このサンプルのようなTransferHandler
を使ったドラッグではMouseMotionListener
でマウスイベントを取得することができないので、DefaultDragSource
にDragSourceMotionListener
を追加してドラッグ中のカーソル位置を取得しています。
- 注:
DragSourceDragEvent#getLocation()
で取得できる位置は、スクリーン上でのマウス位置なので、MouseEvent#getPoint()
の場合のようにSwingUtilities.convertPointToScreen(pt, c);
で変換しなくて良い
参考リンク
コメント
OSX
などの場合はどうなるか不明(テストしていない)。 -- ateraiOSX
でも表示しましたよ。ただクリックした時にアイコン周りに枠が表示されるのですが、その位置がアイコンとずれてます -- nsby?- ありがとうございます。Bug ID: 4874070 invoking DragSource's startDrag with an Image renders no image on dragあたりの修正の詳しい内容がよく分かっていないので、逆に
Mac OS X
では競合する(二重になる)のでは?と思っていました。「アイコン周りの枠」はオフセットを変更するか、クリックした時点でJPanel
からは削除してしまえば、何とかなるかもしれません。 -- aterai
- ありがとうございます。Bug ID: 4874070 invoking DragSource's startDrag with an Image renders no image on dragあたりの修正の詳しい内容がよく分かっていないので、逆に
Web Start
で起動すると、window.setAlwaysOnTop(true);
でAccessControlException
が発生するのを修正。 -- aterai