Swing/CenterFrame のバックアップの現在との差分(No.16)
TITLE:JFrameをスクリーン中央に表示
JFrameをスクリーン中央に表示
Posted by terai at 2004-01-07- category: swing folder: CenterFrame title: JFrameをスクリーン中央に表示 tags: [JFrame] author: aterai pubdate: 2003-12-29T15:48:20+09:00 description: JFrameやJDialogなどのWindowがスクリーンの中央に配置されるように設定します。 image:
概要
JFrame
やJDialog
などのWindow
がスクリーンの中央に配置されるように設定します。
Screenshot
Advertisement
概要
フレームやダイアログなどをスクリーンの中央に表示します。- &jnlp;
- &jar;
- &zip;
#screenshot
サンプルコード
#spanend
#spanadd
* サンプルコード [#sourcecode]
#spanend
#spanadd
#code(link){{
#spanend
JFrame frame = new JFrame("フレームをスクリーン中央に表示");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
#spandel
//以下は自前で位置を計算する場合
#spanend
#spandel
//Rectangle screen = frame.getGraphicsConfiguration().getBounds();
#spanend
#spandel
//frame.setLocation(screen.x + screen.width/2 - frame.getSize().width/2,
#spanend
#spandel
// screen.y + screen.height/2 - frame.getSize().height/2);
#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
frame.setVisible(true);
解説
JFrame#setLocationRelativeToメソッドで、基準となる親ウィンドウをnullにすると、そのフレームは画面中央に表示されます。解説
Window#setLocationRelativeTo(Component)
メソッドで引数で指定した基準となるコンポーネントをnull
にした場合、JFrame
は画面中央に配置されます。
JFrame#setLocationメソッドで任意の位置を指定する場合は、フレームの左上隅座標を計算してやります。
-
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)
でそのサイズを設定した後で実行する必要がある
コメント
-
1.4
以降なら、setLocationRelativeTo(null)
でも中央になりますよ。 -- Wata- こんな方法があるのですね。参考になりました。 -- aterai
- というわけで、
src.zip
などを更新してみました。ありがとうございました。 -- aterai
参考リンク
コメント
- 1.4以降なら、setLocationRelativeTo(null)でも中央になりますよ。 -- Wata?
- こんな方法があったんですね。参考になりました。 -- terai
- というわけで、src.zipなどを更新してみました。 -- terai