简体   繁体   中英

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. 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.

The buttons are actually JMenuItem in my code, but I wrote them here as JButton to make things easier and straight forward.

Here's my code:

call from my Parent 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

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.

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