繁体   English   中英

如何创建新的JFrame,将谁的位置设置在另一个JFrame的中间?

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

我是Java的新手,这是我想要做的:

我有frame1 ,它具有一个JButton ,一旦单击它,就会在frame1顶部创建一个新的JFrame ,我将其称为frame2 我基本上要frame2中的中间要创建frame1 我该怎么做呢?

您相对于frame1的位置设置frame2的位置。

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

这应该将frame2放在frame1的顶部。

最简单的方法是Marv,但是如果您想用Maths做,可以试试看。

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);

这将frame2frame1顶部居中。
如果你选择了.setLocationRelativeTo()方法,别忘了再利用frame2.setVisible(true) ,如果你没有frame2.setVisible(true)之前frame1.setVisible(true)

使用setLocationRelativeTo(Component c) (如果使用Java 8,请使用此文档 ),如下所示:

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

您还可以使用以下方法将组件在屏幕中居中

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

如果您仍然遇到问题,请查看问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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