简体   繁体   English

JDialog不在父JFrame上居中

[英]JDialog not centered over parent JFrame

I am trying to get my JDialog to popup in the center of my JFrame on a button click. 我试图让我的JDialog在单击按钮时弹出到JFrame的中心。 I have JOptionPanel that popup correctly over the parent JFrame, but the JDialog is popping up relative to the JFrame but not in the center. 我有JOptionPanel可以在父JFrame上正确弹出,但是JDialog是相对于JFrame弹出而不是在中心弹出。

The buttons are actually JMenuItem in my code, but I wrote them here as JButton to make things easier and straight forward. 这些按钮实际上是我的代码中的JMenuItem,但是我在这里将它们写为JButton来使事情变得简单而直接。

Here's my code: 这是我的代码:

call from my Parent JFrame: 从我的父级JFrame调用:

JButton about = new JButton("About");
about.addActionListener(new ActionListener() { //this one IS NOT in the center of MyJFrame
                public void actionPerformed(ActionEvent e) {
                    new AboutDialog(MyJFrame.this);
                }
            });


JButton exit = new JButton("Exit");
exit.addActionListener(new ActionListener() { //this one IS in the center of MyJFrame
                    public void actionPerformed(ActionEvent e) {
                        if(JOptionPane.showConfirmDialog(MyJFrame.this, "Are you sure you want to exit ?","",JOptionPane.YES_NO_OPTION) == 0)
                            System.exit(0);
                    }
                });

AboutDialog Class AboutDialog类

public class AboutDialog extends JDialog{
public AboutDialog(JFrame parent) {
        setLocationRelativeTo(parent);
        setLayout(new BorderLayout());
...

对话框未居中

JOptionPanel正确居中

Thank you 谢谢

setLocationRelativeTo(parent);

The above code needs to be executed AFTER you have added all the components to the dialog and packed the dialog and before you make the dialog visible. 在将所有组件添加到对话框并打包对话框之后以及使对话框可见之前,需要执行以上代码。

In your current code the size of the dialog is (0, 0) so it can't be centered properly. 在您当前的代码中,对话框的大小为(0,0),因此无法正确居中。

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

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