二点原因がありそうです。
以下、チュートリアルから引用:
Window#setLocationRelativeTo(...)
Position the window so that it is centered over the specified component. If the argument is null, the window is centered onscreen. To properly center the window, you should invoke this method after the window size has been set.
指定したコンポーネントの中央になるようにウィンドウを配置します。 引数がnullの場合、ウィンドウは画面の中央に配置されます。 ウィンドウを適切に中央に配置するには、ウィンドウサイズが設定された後にこのメソッドを呼び出す必要があります。
とのことなので、まずthis.setSize(320, 240);
したあとでthis.setLocationRelativeTo(null);
を呼ぶように変更すると良いのではないでしょうか。
もう一点は、JFrame
などのSwing
コンポーネントを呼び出す場合はSwingUtilities.invokeLater(...)
などを使ってEvent Dispatch Thread上で行う必要があることです。
The Event Dispatch Thread (The Java™ Tutorials > Creating a GUI With JFC/Swing > Concurrency in Swing)
Programs that ignore this rule may function correctly most of the time, but are subject to unpredictable errors that are difficult to reproduce.
このルールを無視するプログラムは、ほとんどの場合正しく機能しますが、再現するのが困難な予測不可能なエラーが発生する可能性があります。
サンプルコード
java
1import javax.swing.*;
2
3public class MainFrame extends JFrame{
4 public MainFrame() {
5 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
6 //this.setLocationRelativeTo(null);
7 this.setSize(320, 240);
8 this.setLocationRelativeTo(null);
9 this.setVisible(true);
10 }
11 public static void main(String[] args) {
12 SwingUtilities.invokeLater(() -> new MainFrame());
13 }
14}