Swing/CenterFrame のバックアップの現在との差分(No.5)
#navi(contents-page-name): No such page: ST
2021-09-24 (金) 14:46:58
概要
JFrame
やJDialog
などのWindow
がスクリーンの中央に配置されるように設定します。
Screenshot
Advertisement
サンプルコード
#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, Kotlinframe.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
- どちらの場合も
JFrame
をpack()
、またはsetSize(int, int)
でそのサイズを設定した後で実行する必要がある
コメント
-
1.4
以降なら、setLocationRelativeTo(null)
でも中央になりますよ。 -- Wata- こんな方法があるのですね。参考になりました。 -- aterai
- というわけで、
src.zip
などを更新してみました。ありがとうございました。 -- aterai