问题

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);

但安德鲁汤普森有不同的意见,而是打电话

frame.pack();
frame.setLocationByPlatform(true);

和询问的思想想知道为什么?


#1 热门回答(156 赞)

在我看来,屏幕中间的GUI看起来如此......"splash-screen'ish"。我一直在等他们消失,然后出现了!

从Java 1.5开始,我们已经访问了Window.setLocationByPlatform(boolean)。哪一个..

设置此窗口是否应显示在本机窗口系统的默认位置,或者在下次使窗口可见时显示在当前位置(由getLocation返回)。此行为类似于显示的本机窗口,没有以编程方式设置其位置。如果未明确设置其位置,则大多数窗口系统会级联窗口。一旦窗口显示在屏幕上,就确定实际位置。

看看这个示例的效果,它将3个GUI放入操作系统选择的默认位置 - 在Windows 7,Linux与Gnome和Mac OS X上。

Stacked windows on Windows 7

enter image description here

Stacked windows on Mac OS X

(3批)3个整齐堆叠的图形用户界面。这代表了最终用户的"最小惊喜之路",因为它是操作系统如何定位默认纯文本编辑器的3个实例(或其他任何东西)。我要感谢Linux和Mac的trashgod。图片。

这是使用的简单代码:

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();
            }
        });
    }
}

#2 热门回答(3 赞)

我完全同意setLocationByPlatform(true)是指定新JFrame位置的最好方法,但是在a双显示器设置你可能会遇到问题。在我的例子中,子JFrame是在"另一个"监视器上生成的。示例:我在屏幕2上有我的主GUI,我启动了一个新的JFrame withsetLocationByPlatform(true),它在屏幕1上打开。所以这是一个更完整的解决方案,我认为:

...
        // Let the OS try to handle the positioning!
        f.setLocationByPlatform(true);
        if( !f.getBounds().intersects(MyApp.getMainFrame().getBounds()) ) {

          // non-cascading, but centered on the Main GUI
          f.setLocationRelativeTo(MyApp.getMainFrame()); 
        }
        f.setVisible(true);

原文链接