在 another thread我说过我喜欢通过执行以下操作来使我的 GUI 居中:
JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new HexagonGrid());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
但 Andrew Thompson 有不同的意见,改为调用
frame.pack();
frame.setLocationByPlatform(true);
好奇的人想知道为什么?
最佳答案
在我看来,屏幕中间的 GUI 看起来如此..“闪屏”。我一直在等待它们消失,真正的 GUI 出现!
从 Java 1.5 开始,我们可以访问 Window.setLocationByPlatform(boolean)
.哪个..
Sets whether this Window should appear at the default location for the native windowing system or at the current location (returned by getLocation) the next time the Window is made visible. This behavior resembles a native window shown without programmatically setting its location. Most windowing systems cascade windows if their locations are not explicitly set. The actual location is determined once the window is shown on the screen.
看看这个示例的效果,它将 3 个 GUI 置于操作系统选择的默认位置 - 在 Windows 7、带有 Gnome 的 Linux 和 Mac OS X 上。
(3 批)3 个 GUI 整齐堆叠。这代表了最终用户的“最不意外的路径”,因为它是操作系统如何定位默认纯文本编辑器(或其他任何东西)的 3 个实例的方式。感谢 Linux 和 Mac 的垃圾神。图片。
这里是使用的简单代码:
import javax.swing.*;
class WhereToPutTheGui {
public static void initGui() {
for (int ii=1; ii<4; ii++) {
JFrame f = new JFrame("Frame " + ii);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
String s =
"os.name: " + System.getProperty("os.name") +
"\nos.version: " + System.getProperty("os.version");
f.add(new JTextArea(s,3,28)); // suggest a size
f.pack();
// Let the OS handle the positioning!
f.setLocationByPlatform(true);
f.setVisible(true);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {}
initGui();
}
});
}
}
关于java - 如何最好地定位 Swing GUI?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7143287/