[英]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);
這將frame2
在frame1
頂部居中。
如果你選擇了.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.