Swing/CenterFrame のバックアップの現在との差分(No.12)
TITLE:JFrameをスクリーン中央に表示
JFrameをスクリーン中央に表示
編集者:Terai Atsuhiro~
作成日:2004-01-07
更新日:2021-09-24 (金) 14:46:58
概要
JFrame
やJDialog
などのWindow
がスクリーンの中央に配置されるように設定します。
Screenshot
Advertisement
概要
フレームやダイアログなどをスクリーンの中央に表示します。サンプルコード
#spanend
#spanadd
JFrame frame = new JFrame("フレームをスクリーン中央に表示");
#spanend
#spanadd
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
#spanend
#spanadd
frame.getContentPane().add(new MainPanel());
#spanend
#spanadd
frame.pack();
#spanend
#spanadd
frame.setLocationRelativeTo(null);
#spanend
#spanadd
// 以下は自前で中央配置になる位置を計算する場合
#spanend
#spanadd
// Rectangle screen = frame.getGraphicsConfiguration().getBounds();
#spanend
#spanadd
// frame.setLocation(screen.x + screen.width / 2 - frame.getSize().width / 2,
#spanend
#spanadd
// screen.y + screen.height / 2 - frame.getSize().height / 2);
#spanend
#spanadd
frame.setVisible(true);
#spanend
#spanadd
View in GitHub: Java, Kotlin解説
Window#setLocationRelativeTo(Component)
メソッドで引数で指定した基準となるコンポーネントをnull
にした場合、JFrame
は画面中央に配置されます。
サンプルコード
JFrame frame = new JFrame("フレームをスクリーン中央に表示"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); //以下は自前で位置を計算する場合 //Rectangle screen = frame.getGraphicsConfiguration().getBounds(); //frame.setLocation(screen.x + screen.width/2 - frame.getSize().width/2, // screen.y + screen.height/2 - frame.getSize().height/2); frame.setVisible(true);
-
JFrame
の左上隅座標を計算してJFrame#setLocation(...)
メソッドを使用し、JFrame
を画面中央に配置する方法もある#spanend #spanadd Rectangle screen = frame.getGraphicsConfiguration().getBounds(); #spanend #spanadd frame.setLocation( #spanend screen.x + screen.width / 2 - frame.getSize().width / 2, screen.y + screen.height / 2 - frame.getSize().height / 2); #spanadd
- どちらの場合も
JFrame
をpack()
、またはsetSize(int, int)
でそのサイズを設定した後で実行する必要がある
- &jnlp;
- &jar;
- &zip;
コメント
-
1.4
以降なら、setLocationRelativeTo(null)
でも中央になりますよ。 -- Wata- こんな方法があるのですね。参考になりました。 -- aterai
- というわけで、
src.zip
などを更新してみました。ありがとうございました。 -- aterai
解説
JFrame#setLocationRelativeToメソッドで、基準となる親ウィンドウをnullにすると、そのフレームは画面中央に表示されます。 JFrame#setLocationメソッドで任意の位置を指定する場合は、フレームの左上隅座標を計算してやります。 どちらも、フレームをpack()したあとで実行するようにしてください。参考リンク
コメント
- 1.4以降なら、setLocationRelativeTo(null)でも中央になりますよ。 -- Wata?
- こんな方法があったんですね。参考になりました。 -- terai
- というわけで、src.zipなどを更新してみました。 -- terai