JDialog 出现在屏幕的左上角,当我将它的位置设置为其父级的中心时

JDialog appears in the top left corner of screen, when when I've set it's position to the center of its parent

在我将对话框初始化为

之前
  addQuestionDialog = new JDialog(SwingUtilities.windowForComponent(this),"Add    question);

我通过调用以下命令将对话框的位置设置在其父对话框的中心:

addQuestionDialog.setLocationRelativeTo(this)

这有效并在其父级的中心显示对话框,但是当我将对话框设置为模态对话框时,它完全忽略设置方法并在我的屏幕左上角显示对话框。

addQuestionDialog = new JDialog(SwingUtilities.windowForComponent(this),"Add question", Dialog.ModalityType.DOCUMENT_MODAL);

however when I set the dialog to be a modal dialog, it completely ignores the set method and displays the dialog in the top left corner of my screen.

代码的顺序应该是:

dialog.setLocationRelativeTo(..);
dialog.setVisible(true );

我猜你正在使用:

dialog.setVisible(true );
dialog.setLocationRelativeTo(..); // this is not executed until the dialog is closed.

这个 JDialog 代码序列对我有用:

   setModal(true)
   pack()
   setLocationRelativeTo(frame)
   setVisible(true)

将 setLocationRelativeTo(frame) 行放在 pack() 行之前会导致 off-center 放置对话框。有意思。:)