2021-09-24 (金) 14:46:58
  • category: swing folder: CenterFrame title: JFrameをスクリーン中央に表示 tags: [JFrame] author: aterai pubdate: 2003-12-29T15:48:20+09:00 description: JFrameやJDialogなどのWindowがスクリーンの中央に配置されるように設定します。 image: https://lh3.googleusercontent.com/_9Z4BYR88imo/TQTIvEn-69I/AAAAAAAAATQ/Fw4dLY4C0EE/s800/CenterFrame.png

概要

JFrameJDialogなどのWindowがスクリーンの中央に配置されるように設定します。

サンプルコード

#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
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);

解説

Window#setLocationRelativeTo(Component)メソッドで引数で指定した基準となるコンポーネントをnullにした場合、JFrameは画面中央に配置されます。
  • 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
    
  • どちらの場合もJFramepack()、またはsetSize(int, int)でそのサイズを設定した後で実行する必要がある

コメント