• 追加された行はこの色です。
  • 削除された行はこの色です。
---
category: swing
folder: MagneticFrame
title: JDesktopPaneにJInternalFrameを吸着させる
tags: [DesktopManager, JDesktopPane, JInternalFrame]
author: aterai
pubdate: 2007-01-01T08:38:12+09:00
description: JDesktopPaneとJInternalFrameの距離が近くなった場合、これらを自動的に吸着させます。
image: https://lh4.googleusercontent.com/_9Z4BYR88imo/TQTPnXoiDZI/AAAAAAAAAeQ/9SMGwoIqOi8/s800/MagneticFrame.png
---
* 概要 [#summary]
`JDesktopPane`と`JInternalFrame`の距離が近くなった場合、これらを自動的に吸着させます。

#download(https://lh4.googleusercontent.com/_9Z4BYR88imo/TQTPnXoiDZI/AAAAAAAAAeQ/9SMGwoIqOi8/s800/MagneticFrame.png)

* サンプルコード [#sourcecode]
#code(link){{
desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
desktop.setDesktopManager(new MagneticDesktopManager());

// ...
class MagneticDesktopManager extends DefaultDesktopManager {
  @Override public void dragFrame(JComponent frame, int x, int y) {
    Container c = SwingUtilities.getAncestorOfClass(JDesktopPane.class, frame);
    if (c instanceof JDesktopPane) {
      JDesktopPane desktop = (JDesktopPane) c;
      int e = x;
      int n = y;
      int w = desktop.getSize().width - frame.getSize().width - e;
      int s = desktop.getSize().height - frame.getSize().height - n;
      if (isNear(e) || isNear(n) || isNear(w) || isNear(s)) {
        super.dragFrame(frame, getX(e, w), getY(n, s));
      } else {
        super.dragFrame(frame, x, y);
      }
    }
  }

  private static int getX(int e, int w) {
    return e < w ? isNear(e) ? 0 : e : isNear(w) ? w + e : e;
  }

  private static int getY(int n, int s) {
    return n < s ? isNear(n) ? 0 : n : isNear(s) ? s + n : n;
  }

  private static boolean isNear(int c) {
    return Math.abs(c) < 10;
  }
}
}}

* 解説 [#explanation]
`DesktopManager#dragFrame(JInternalFrame,int,int)`メソッドをオーバーライドすることで`JInternalFrame`の配置座標を調整しています。上記のサンプルでは、`JDesktopPane`と`JInternalFrame`の距離が`10px`以下になった場合、それぞれの辺が吸着するよう設定しています。

* 参考リンク [#reference]
- [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/DefaultDesktopManager.html#dragFrame-javax.swing.JComponent-int-int- DefaultDesktopManager#dragFrame(...) (Java Platform SE 8)]

* コメント [#comment]
#comment
#comment