Java: JFrame.setLocationRelativeTo(null) not centering the window on Ubuntu 10.04 / gnome 2.30.2 with OpenJDK 1.6.0_18(Java:JFrame.setLocationRelativeTo(null) 不在 Ubuntu 10.04/gnome 2.30.2 和 OpenJDK 1.6.0_18 上的窗口居中)
问题描述
示例代码:
JFrame jFrame = new JFrame("Test");
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setLocationRelativeTo(null);
jFrame.setSize(600, 600);
jFrame.pack();
// jFrame.setLocationRelativeTo(null); // same results
jFrame.setVisible(true);
这是 OpenJDK 的错吗?我记得听说它不如 Sun 的好,但自从它成为 Ubuntu 或任何我决定采用它的标准之后.该程序可能会在 Windows 上运行,所以我想我必须在那里检查...有什么简单的方法可以以独立于平台的方式解决这个问题,而不会破坏它已经工作的地方?
Is this the OpenJDK's fault? I recall hearing it wasn't as good as Sun's, but since it became the standard for Ubuntu or whatever I decided to go along with it. The program is probably gonna run on windows, so I suppose I'm gonna have to check there... Any easy way to fix this in a platform independent way without breaking it where it already works?
推荐答案
一种方法是手动定位窗口.在您调用 pack()
之后立即添加以下代码.
One way is to manually position the window. Put the following code right after your call to pack()
.
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Point middle = new Point(screenSize.width / 2, screenSize.height / 2);
Point newLocation = new Point(middle.x - (jFrame.getWidth() / 2),
middle.y - (jFrame.getHeight() / 2));
jFrame.setLocation(newLocation);
免责声明,这仅在 Windows 上进行了测试.
此外,您应该始终使用 setPreferredSize()
而不是 setSize()
.
Also, you should always use setPreferredSize()
instead of setSize()
.
这篇关于Java:JFrame.setLocationRelativeTo(null) 不在 Ubuntu 10.04/gnome 2.30.2 和 OpenJDK 1.6.0_18 上的窗口居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java:JFrame.setLocationRelativeTo(null) 不在 Ubuntu 10.04/gnome 2.30.2 和 OpenJDK 1.6.0_18 上的窗口居中


基础教程推荐
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 从 python 访问 JVM 2022-01-01