user2603506
user2603506

Reputation: 23

How do I create a new JFrame, whos' location is set to the middle of another JFrame?

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?

Upvotes: 0

Views: 87

Answers (3)

Chris Sprague
Chris Sprague

Reputation: 740

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.

Upvotes: 0

Charlie
Charlie

Reputation: 986

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)

Upvotes: 0

Marv
Marv

Reputation: 3557

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.

Upvotes: 3

Related Questions