Question

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

Dialog NOT Centered

JOptionPanel Centered Correctly

Thank you

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top