The easiest way to do it is Marv's, but if you want to do it with Maths, try this instead.
Point offSet=frame1.getLocation();
Dimension loc1=frame1.getSize();
Dimension loc2=frame2.getSize();
double newX=offSet.getX()+loc1.getWidth()/2.0-loc2.getWidth()/2.0;
double newY=offSet.getY()+loc1.getHeight()/2.0-loc2.getHeight()/2.0;
frame2.setLocation((int)Math.floor(newX), (int)Math.floor(newY));
frame2.setVisible(true);
This will center frame2
on top of frame1
.
If you choose the .setLocationRelativeTo()
method, don't forget to re-use frame2.setVisible(true)
if you did frame2.setVisible(true)
before frame1.setVisible(true)