java - 使用 JOptionPane.showMessageDialog 居中对话框

标签 java swing

我一直使用类似于下面的代码来显示对话框:

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/

相关文章:

java - 访问 https ://www. googleapis.com/oauth2/v1/certs 时出现 404 错误

java - 为什么我的 SpringLayout 与示例不同?

java - 如何动态调用java方法?

java - QStackedWidget 相当于 Java Swing

java - 在屏幕上的任何位置隐藏 Java 光标

java - 检索到的数据库数据出现交叉脚本错误

java - 使用字符串选项优化 if-else/switch-case

java - 使用 netbeans GUI 构建器 JSlider 放大 JLabel 图标

java - JFrame 不显示

java - JButton如何设置滚动图标边界