Summary
JWindowなどのタイトルバーのないフレームをマウスで移動します。
Screenshot
Source Code Examples
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 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
Description
JWindowやsetUndecorated(true)したJFrameのようにタイトルバーのないフレームをマウスのドラッグで移動します。実際はJWindow自体にリスナーを設定するのではなく子コンポーネントにMouseMotionListenerなどを追加しています。
上記のサンプルではJLabelにリスナーを追加し、これをJWindowに配置してドラッグ可能にしています。
- スプラッシュスクリーンの次に開く
JFrameはJFrame#setUndecorated(true)を設定してタイトルバーなどは非表示
- 代わりに青いラベル部分をドラッグ可能に設定
- マルチディスプレイなどで別画面に移動できないバグ?を修正
- ただし
Web StartのSandBox内では以前と同じく画面の外までは移動不可?
JNLPのセキュリティにall-permissionsを設定する必要がある
Swing Tutorialの FrameDemo2で試しても、同様?
Look and feel decorated: 画面外に移動不可
Window system decorated: 画面外に移動可能
Reference
Comment