• title: JWindowをマウスで移動 tags: [JWindow, JFrame, MouseListener, MouseMotionListener] author: aterai pubdate: 2004-09-06 description: JWindowなどのタイトルバーのないフレームをマウスで移動します。

概要

JWindowなどのタイトルバーのないフレームをマウスで移動します。

サンプルコード

public void createSplashScreen(String path) {
  ImageIcon img = new ImageIcon(getClass().getResource(path));
  DragWindowListener dwl = new DragWindowListener();
  splashLabel = new JLabel(img);
  splashLabel.addMouseListener(dwl);
  splashLabel.addMouseMotionListener(dwl);
  splashScreen = new JWindow(getFrame());
  splashScreen.getContentPane().add(splashLabel);
  splashScreen.pack();
  splashScreen.setLocationRelativeTo(null);
}
class DragWindowListener extends MouseAdapter {
  private final Point startPt = new Point();
  //private Point  loc;
  private Window window;
  @Override public void mousePressed(MouseEvent me) {
    startPt.setLocation(me.getPoint());
  }
  @Override public void mouseDragged(MouseEvent me) {
    if (window == null) {
      window = SwingUtilities.windowForComponent(me.getComponent());
    }
    Point eventLocationOnScreen = me.getLocationOnScreen();
    window.setLocation(eventLocationOnScreen.x - startPt.x,
                       eventLocationOnScreen.y - startPt.y);
    //loc = window.getLocation(loc);
    //int x = loc.x - start.getX() + me.getX();
    //int y = loc.y - start.getY() + me.getY();
    //window.setLocation(x, y);
  }
}
View in GitHub: Java, Kotlin

解説

JWindowや、setUndecorated(true)したJFrameのようにタイトルバーのないフレームをマウスのドラッグで移動します。実際はJWindowに、MouseMotionListenerなどを実装したコンポーネントを追加しています。

上記のサンプルでは、Splash ScreenJLabelにリスナーを追加し、これをJWindowに貼り付けてドラッグできるようにしています。

次に開くsetUndecorated(true)したJFrameでは、青いラベル部分をドラッグすることが出来ます。


  • マルチディスプレイなどで、別画面に移動できないバグ?を修正。
    • ただし、Web StartSandBox内では、以前と同じく画面の外に移動することができない?
      • JNLPのセキュリティにall-permissionsを設定する必要がある
  • Swing TutorialFrameDemo2で試しても、同様?
    • Look and feel decorated: 画面外に移動不可
    • Window system decorated: 画面外に移動可能

参考リンク

コメント