我一直使用类似于下面的代码来显示对话框:
JOptionPane.showMessageDialog(JOptionPane.getFrameForComponent(this), … yada
但是,我现在认为这是“更正确的”:
JOptionPane.showMessageDialog(getRootPane(), … yada
人们喜欢/推荐什么?
最佳答案
没有一个是“更正确”的——这取决于你想要什么样的效果。来自JOptionPane JavaDocs -
parentComponent : Defines the Component that is to be the parent of this dialog box. It is used in two ways: the Frame that contains it is used as the Frame parent for the dialog box, and its screen coordinates are used in the placement of the dialog box. In general, the dialog box is placed just below the component. This parameter may be null, in which case a default Frame is used as the parent, and the dialog will be centered on the screen (depending on the L&F).
在您的情况下,您希望对话框以框架为中心 - JOptionPane.getFrameForComponent(component) 或 SwingUtilities.getWindowAncestor(component) 从任何组件工作; getRootPane() 仅适用于 RootPaneContainer(即可能是 JFrame),您不妨在该上下文中使用“this”。
关于java - 使用 JOptionPane.showMessageDialog 居中对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1265533/