TITLE:JFrameをスクリーン中央に表示

Posted by at 2003-12-29

JFrameをスクリーン中央に表示

フレームやダイアログなどをスクリーンの中央に表示します。

  • &jnlp;
  • &jar;
  • &zip;
CenterFrame.png

サンプルコード

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);
View in GitHub: Java, Kotlin

解説

`JFrame#setLocationRelativeToメソッドで、基準となる親ウィンドウをnull`にすると、そのフレームは画面中央に表示されます。

`JFrame#setLocation`メソッドで任意の位置を指定する場合は、フレームの左上隅座標を計算します。

どちらも、フレームを`pack()、もしくはsetSize(int,int)`した後で実行するようにしてください。

参考リンク

コメント

  • `1.4以降なら、setLocationRelativeTo(null)`でも中央になりますよ。 -- Wata
    • こんな方法があったんですね。参考になりました。 -- aterai
    • というわけで、`src.zip`などを更新してみました。ありがとうございました。 -- aterai