如何根据父JFrame设置JDialog位置?

时间:2014-01-20 08:06:55

标签: java swing jframe jdialog

我的系统中有一个父框架,我需要在Click上显示一个对话框。但我需要在父框架的中间显示该对话框。整天。并且父框架位置可能不会始终相同。那么如何将它设置在中间?

我正在研究摇摆JFrame

com.verve.visdashboard.NewOkCancelDialog cancelDialog = new com.verve.visdashboard.NewOkCancelDialog(new FrameOwnserPnael(), true);
cancelDialog.setLocationRelativeTo(new FrameOwnserPnael());
cancelDialog.setLocationByPlatform(true);

3 个答案:

答案 0 :(得分:2)

只需对JDialog使用setLocationRelativeTo()方法。

JDialog d = new JDialog();
d.setLocationRelativeTo(COMPONENT);

此处COMPONENT是父框架。

答案 1 :(得分:1)

基本代码应为:

JDialog dialog = new CustomDialog(...);
dialog.pack();
dialog.setLocationRelativeTo( parentFrame );

在使用pack()方法之前,对话框的大小为(0,0),因此对话框无法正确居中。

答案 2 :(得分:0)

每次创建新的父框架。相反,您应该只创建一次父帧,并使用该对象将其作为参数传递。

FrameOwnserPnael parentFrame = new FrameOwnserPnael();
com.verve.visdashboard.NewOkCancelDialog cancelDialog = new com.verve.visdashboard.NewOkCancelDialog(parentFrame, true);
cancelDialog.setLocationRelativeTo(parentFrame);
cancelDialog.setLocationByPlatform(true);
相关问题