---
title: JDesktopPaneにJInternalFrameを吸着させる
tags: [DesktopManager, JDesktopPane, JInternalFrame]
author: aterai
pubdate: 2007-01-01T08:38:12+09:00
description: JDesktopPaneとJInternalFrameの距離が近くなった場合、これらを自動的に吸着させます。
---
* 概要 [#t9488112]
`JDesktopPane`と`JInternalFrame`の距離が近くなった場合、これらを自動的に吸着させます。

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

* サンプルコード [#o8501b2d]
#code(link){{
desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
desktop.setDesktopManager(new DefaultDesktopManager() {
  @Override public void dragFrame(JComponent frame, int x, int y) {
    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)) {
      x = (e<w)?(isNear(e)?0:e):(isNear(w)?w+e:e);
      y = (n<s)?(isNear(n)?0:n):(isNear(s)?s+n:n);
    }
    super.dragFrame(frame, x, y);
  }
  private boolean isNear(int c) {
    return (Math.abs(c)<10);
  }
});
}}

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

//* 参考リンク
* コメント [#y9744126]
#comment
#comment