• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JWindowをマウスで移動
#navi(../)
*JWindowをマウスで移動 [#g9940ceb]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2004-09-06~
更新日:&lastmod;

#contents

**概要 [#e0c286a5]
JWindowなどのタイトルバーのないフレームをマウスで移動します。

#screenshot

**サンプルコード [#r3a65b7b]
#code{{
public void createSplashScreen(String path) {
  ImageIcon img = new ImageIcon(getClass().getResource(path));
  DragWindowListener dwl = new DragWindowListener();
  splashLabel = new JLabel(img);
  splashLabel.addMouseListener(new MyMouseListener());
  splashLabel.addMouseMotionListener(new MyMouseMotionListener());
  splashLabel.addMouseListener(dwl);
  splashLabel.addMouseMotionListener(dwl);
  splashScreen = new JWindow(getFrame());
  splashScreen.getContentPane().add(splashLabel);
  splashScreen.pack();
  splashScreen.setLocationRelativeTo(null);
}
private MouseEvent start;
class MyMouseListener extends MouseAdapter {
class DragWindowListener extends MouseInputAdapter { // JDK 6 -> MouseAdapter {
  private MouseEvent start;
  private Point  loc;
  private Window window;
  public void mousePressed(MouseEvent me) {
    start = me;
  }
}
class MyMouseMotionListener extends MouseMotionAdapter {
  private Point  loc;
  private Window frame;
  public void mouseDragged(MouseEvent me) {
    if(frame==null) {
      Component cmp = (Component)me.getSource();
      frame = SwingUtilities.windowForComponent(cmp);
    if(window==null) {
      window = SwingUtilities.windowForComponent((Component)me.getSource());
    }
    loc = frame.getLocation(loc);
    loc = window.getLocation(loc);
    int x = loc.x - start.getX() + me.getX();
    int y = loc.y - start.getY() + me.getY();
    frame.setLocation(x, y);
    window.setLocation(x, y);
  }
}
}}
-&jnlp;
-&jar;
-&zip;

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

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

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

//**参考リンク
**コメント [#hfe1ff82]
#comment