gpt4 book ai didi

java - JDialog 未在父 JFrame 上居中

转载 作者:行者123 更新时间:2023-12-01 17:15:02 25 4
gpt4 key购买 nike

我试图让我的 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());
...

Dialog NOT Centered

JOptionPanel Centered Correctly

谢谢

最佳答案

setLocationRelativeTo(parent);

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

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

关于java - JDialog 未在父 JFrame 上居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22615010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com