Swing/DockingFrames のバックアップの現在との差分(No.8)
TITLE:JFrameの移動を同期
JFrameの移動を同期
編集者:Terai Atsuhiro~
作成日:2005-07-09
更新日:2023-07-01 (土) 01:07:39
概要
JFrame
を2
つ並べて作成し、その位置関係を保ったまま移動できるようにします。
Screenshot
Advertisement
概要
JFrameを2つ並べて作成し、その位置関係を保ったまま移動できるようにします。サンプルコード
#spanend
#spanadd
private void positionFrames(ComponentEvent e) {
#spanend
if (e.getComponent().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);
}
#spanadd
}
#spanend
#spanadd
View in GitHub: Java, Kotlin#screenshot
解説
-
JFrame
を上下に並べてそれぞれにComponentListener
を実装したリスナーを追加 - 片方のフレームが移動された時、残りのフレームの位置を指定する前に一旦このリスナーを削除することで処理ループの発生を防止
サンプルコード
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); } }
参考リンク
- Swing (Archive) - how to dock two jdialogs?
- Swing (Archive) - how to catch drag event in the title bar of a jframe
- ComponentListener (Java Platform SE 8)
- &jnlp;
- &jar;
- &zip;
解説
上記のサンプルでは、JFrameを上下に並べて、それぞれにComponentListenerインタフェースを実装したリスナーを追加しています。片方のフレームが移動された時、残りのフレームの位置を指定する前に、一旦このリスナーを削除してやることで、処理がループしないようになっています。参考リンク
- Java Forums - how to dock two jdialogs?
- Java Forums - how to catch drag event in the title bar of a jframe