简体   繁体   中英

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?

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.

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM