TITLE:JWindowをマウスで移動

Posted by terai at 2004-09-06

JWindowをマウスで移動

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

  • &jnlp;
  • &jar;
  • &zip;

#screenshot

サンプルコード

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 MouseInputAdapter { // JDK 6 -> MouseAdapter {
  private MouseEvent start;
  private Point  loc;
  private Window window;
  public void mousePressed(MouseEvent me) {
    start = me;
  }
  public void mouseDragged(MouseEvent me) {
    if(window==null) {
      window = SwingUtilities.windowForComponent(me.getComponent());
    }
    loc = window.getLocation(loc);
    int x = loc.x - start.getX() + me.getX();
    int y = loc.y - start.getY() + me.getY();
    window.setLocation(x, y);
  }
}

解説

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

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

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

参考リンク

コメント