0

I'm new to Java and this is what I'm trying to do:

I have frame1, which has a JButton that, once clicked, creates a new JFrame on top of frame1, which I call frame2. I basically want frame2 to be created in the middle of frame1. How do I do this?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user2603506
  • 31
  • 1
  • 1
  • 5

3 Answers3

3

You set the location of frame2 relative to the location of frame1.

//Initialize your frames
frame2.setLocationRelativeTo(frame1);

This should place frame2 right on top of frame1.

Marv
  • 3,517
  • 2
  • 22
  • 47
0

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)

Charlie
  • 978
  • 1
  • 7
  • 27
0

Use setLocationRelativeTo(Component c) (use this doc if you're using Java 8) as follows:

// center in parent
frame2.setLocationRelativeTo(frame1);

You can also center the component in the screen using

// center in screen
frame2.setLocationRelativeTo( null );

Check out this question if you're still having issues.

Community
  • 1
  • 1
Chris Sprague
  • 740
  • 1
  • 12
  • 22
  • Don't forget to use [this link](http://docs.oracle.com/javase/8/docs/api/java/awt/Window.html#setLocationRelativeTo-java.awt.Component-) if the OP uses Java 8 – Charlie Dec 13 '14 at 18:00
  • @Charlie I edited the post to include Java 8 doc link. Good call - thanks! (I think Marv's answer perfectly fine anyway.) – Chris Sprague Dec 13 '14 at 18:06