如何最好地定位Swing GUI?

Hov*_*els 124 java user-interface swing

另一个线程中,我说过我喜欢通过做这样的事情来集中我的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);
Run Code Online (Sandbox Code Playgroud)

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

frame.pack();
frame.setLocationByPlatform(true);
Run Code Online (Sandbox Code Playgroud)

和询问的头脑想知道为什么?

And*_*son 166

在我看来,屏幕中间的GUI看起来如此......"splash-screen'ish".我一直在等待它们消失,真正的 GUI出现!

从Java 1.5开始,我们就可以访问了Window.setLocationByPlatform(boolean).哪一个..

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

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

Windows 7上的堆叠窗口 在此输入图像描述 在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();
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @MirroredFate这就是我使用`ii`而不是`i`的原因.当我参加编程比赛时,我经常要从中搜索循环索引,比如说,"+ 1"或"-1"来修复一个错误.在这些情况下,无论我使用哪种编辑器,搜索"ii"都比搜索"i"容易得多.类似地,我使用`jj`和`kk`作为嵌套循环索引.:) (11认同)
  • @AndrewThompson 为什么你的计数器变量是 `ii` 而不仅仅是 `i`?这是否符合某些惯例,还是个人喜好(或者可能完全不同)? (2认同)
  • @MirroredFate 嗯.. 我想我会在那里锁定选项 3,“完全不同的东西”。这正是我第一次用 Basic 编程时所习惯的(是的,很久以前)。懒惰是继续使用的原因,“如果它没有坏,就不要修理它”。 (2认同)

Axe*_*ehl 5

我完全同意这setLocationByPlatform(true)是指定新JFrame位置的最好方法,但在双显示器设置中,您可以解决问题.在我的例子中,子JFrame是在"另一个"监视器上生成的.示例:我在屏幕2上有我的主GUI,我启动了一个新的JFrame,setLocationByPlatform(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);
Run Code Online (Sandbox Code Playgroud)