繁体   English   中英

JDialog不在父JFrame上居中

[英]JDialog not centered over parent JFrame

我试图让我的JDialog在单击按钮时弹出到JFrame的中心。 我有JOptionPanel可以在父JFrame上正确弹出,但是JDialog是相对于JFrame弹出而不是在中心弹出。

这些按钮实际上是我的代码中的JMenuItem,但是我在这里将它们写为JButton来使事情变得简单而直接。

这是我的代码:

从我的父级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类

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

对话框未居中

JOptionPanel正确居中

谢谢

setLocationRelativeTo(parent);

在将所有组件添加到对话框并打包对话框之后以及使对话框可见之前,需要执行以上代码。

在您当前的代码中,对话框的大小为(0,0),因此无法正确居中。

暂无
暂无

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

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