문제

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

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top