• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JDesktopPaneにJInternalFrameを吸着させる
#navi(../)
*JDesktopPaneにJInternalFrameを吸着させる [#t9488112]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2007-01-01~
更新日:&lastmod;

#contents

**概要 [#o18d56cf]
JDesktopPaneとJInternalFrameの距離が近くなった場合、これらを自動的に吸着させます。

#screenshot

**サンプルコード [#o8501b2d]
 private class MagneticListener extends MouseInputAdapter {
   private final JInternalFrame frame;
   private final Point loc = new Point();
   public MagneticListener(JInternalFrame frame) {
     this.frame = frame;
   }
   public void mousePressed(MouseEvent e) {
     Point p1 = frame.getLocation();
     Point p2 = SwingUtilities.convertPoint(frame, e.getPoint(), frame.getDesktopPane());
     loc.setLocation(p2.x-p1.x, p2.y-p1.y);
   }
   public void mouseDragged(MouseEvent me) {
     JDesktopPane desktop = frame.getDesktopPane();
     Point ep = me.getPoint();
     Point pt = SwingUtilities.convertPoint(frame, ep.x-loc.x, ep.y-loc.y, desktop);
     int e = pt.x;
     int n = pt.y;
 desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
 desktop.setDesktopManager(new DefaultDesktopManager() {
   //@override
   public void dragFrame(JComponent frame, int x, int y) {
     if(frame!=magneticFrame) {
       super.dragFrame(frame, x, y); return;
     }
     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)) {
       int x = (e<w)?(isNear(e)?0:e):(isNear(w)?w+e:e);
       int y = (n<s)?(isNear(n)?0:n):(isNear(s)?s+n:n);
       desktop.getDesktopManager().dragFrame(frame,x,y);
       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);
   }
 }
 });

-&jnlp;
-&jar;
-&zip;

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

- 課題
-- アイコン化している時に吸着できない

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