TITLE:JFrameをスクリーン中央に表示
#navi(../)
*JFrameをスクリーン中央に表示 [#b05e1eeb]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2004-01-07~
更新日:&lastmod;

#contents

**概要 [#r4fdfcc6]
フレームやダイアログなどをスクリーンの中央に表示します。

#screenshot

**サンプルコード [#o0de8a54]
 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);

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

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

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

どちらも、フレームをpack()したあとで実行するようにしてください。

**参考リンク [#a98bdd9a]
-[[How can I open a JFrame at the center of my screen ?>http://forum.java.sun.com/thread.jspa?forumID=57&threadID=508444]]

**コメント [#b68bf302]
-1.4以降なら、setLocationRelativeTo(null)でも中央になりますよ。 -- [[Wata]] &new{2004-06-07 (月) 17:47:08};
-こんな方法があったんですね。参考になりました。 -- [[terai]] &new{2004-06-07 (月) 19:26:17};
-というわけで、src.zipなどを更新してみました。 -- [[terai]] &new{2004-06-07 (月) 19:44:21};

#comment