I will provide 3 methods to your question :
You can either use the simplest method to center it, relative to your viewport, which is :
setLocationRelativeTo(null);
The second one, is to use :
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(dim.width/2 - frame.getSize().width/2, dim.height/2 - frame.getSize().height/2);
And the third one, the most customizable one, is a bit more complicated, but is the most useful. (in my opinion) :
1.) You create a JButton and add it to your panel.
2.) You add an ActionListener event to it.
3.) On your button click, you invoke the method :
frame.getLocationOnScreen(); which you need to save to a Point
variable => Point location = frame.getLocationOnScreen;
4.) After that, you invoke : System.out.println(location);, so that you can get the location on the screen that you want to put your frame
to - it will print it to the console.
5.) You delete the button and ActionListener, after you've got the x, y coordinates.
6.) You invoke : frame.setLocation(x, y);
The code looks like this :
JButton button = new JButton();
button.setText("Get Location");
panel.add(button);
ActionListener onButton = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Point location = frame.getLocationOnScreen();
System.out.println(location);
}
};
button.addActionListener(onButton);
After you have the location, do this :
frame.setLocation(445, 195);