Swing/CenterFrame のバックアップの現在との差分(No.24)
- 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
サンプルコード
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);
View in GitHub: Java, Kotlin解説
Window#setLocationRelativeTo(Component)
メソッドで、引数で指定した基準となるコンポーネントが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)
でそのサイズを設定した後で実行する必要がある
pack()
、もしくはsetSize(int, int)
でサイズを設定した後で実行するようにしてください。