• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JWindowをマウスで移動
#navi(../)
#tags()
RIGHT:Posted by &author(aterai); at 2004-09-06
*JWindowをマウスで移動 [#g9940ceb]
JWindowなどのタイトルバーのないフレームをマウスで移動します。

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

//#screenshot
#ref(http://lh6.ggpht.com/_9Z4BYR88imo/TQTL8cG8F0I/AAAAAAAAAYY/vZfyqnyr6-I/s800/DragWindow.png)

**サンプルコード [#r3a65b7b]
#code(link){{
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 MouseEvent start;
  //private Point  loc;
  private Window window;
  @Override public void mousePressed(MouseEvent me) {
    start = me;
  }
  @Override public void mouseDragged(MouseEvent me) {
    if(window==null) {
      window = SwingUtilities.windowForComponent(me.getComponent());
    }
    Point eventLocationOnScreen = me.getLocationOnScreen();
    window.setLocation(eventLocationOnScreen.x - start.getX(),
                       eventLocationOnScreen.y - start.getY());
    //loc = window.getLocation(loc);
    //int x = loc.x - start.getX() + me.getX();
    //int y = loc.y - start.getY() + me.getY();
    //window.setLocation(x, y);
  }
}
}}

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

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

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

----
- マルチディスプレイなどで、別画面に移動できないバグ?を修正。
-- ただし、Web Start のSandBox内では、以前と同じく画面の外に移動することができない?
--- JNLP のセキュリティに all-permissions を設定する必要がある

- Swing Tutorial の [http://docs.oracle.com/javase/tutorial/uiswing/examples/components/index.html#FrameDemo2 FrameDemo2]で試しても、同様?
-- "Look and feel decorated": 画面外に移動不可
-- "Window system decorated": 画面外に移動可能

**参考リンク [#n4c8a267]
-[[JInternalFrameをJFrameとして表示する>Swing/InternalFrameTitleBar]]
-[[JFrameのタイトルバーなどの装飾を独自のものにカスタマイズする>Swing/CustomDecoratedFrame]]

**コメント [#hfe1ff82]
- bloggerの方にコメントをもらって、調査、修正中だけど、dual-monitor 環境が無いのでテストしづらい…。 -- [[aterai]] &new{2010-10-06 (水) 13:01:36};

#comment