TITLE:JFrameの移動を同期
#navi(../)
#tags(JFrame, ComponentListener)
RIGHT:Posted by &author(aterai); at 2005-07-04
*JFrameの移動を同期 [#qa088c78]
``JFrame``を``2``つ並べて作成し、その位置関係を保ったまま移動できるようにします。

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

//#screenshot
#ref(http://lh4.ggpht.com/_9Z4BYR88imo/TQTLtEL3M0I/AAAAAAAAAYA/9HmyXI1Uw0M/s800/DockingFrames.png)

**サンプルコード [#f580c5f3]
#code(link){{
private void positionFrames(ComponentEvent e) {
  if(e.getSource().equals(frame1)) {
    int x = frame1.getBounds().x;
    int y = frame1.getBounds().y + frame1.getBounds().height;
    frame2.removeComponentListener(this);
    frame2.setLocation(x, y);
    frame2.addComponentListener(this);
  }else{
    int x = frame2.getBounds().x;
    int y = frame2.getBounds().y - frame1.getBounds().height;
    frame1.removeComponentListener(this);
    frame1.setLocation(x, y);
    frame1.addComponentListener(this);
  }
}
}}

**解説 [#ceedca5e]
上記のサンプルでは、``JFrame``を上下に並べて、それぞれに``ComponentListener``インタフェースを実装したリスナーを追加しています。片方のフレームが移動された時、残りのフレームの位置を指定する前に、一旦このリスナーを削除してやることで、処理がループしないようになっています。

**参考リンク [#q31d1b00]
- [http://forums.sun.com/thread.jspa?threadID=545918 Swing (Archive) - how to dock two jdialogs?]
- [http://forums.sun.com/thread.jspa?threadID=429463 Swing (Archive) - how to catch drag event in the title bar of a jframe]

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