java - 如何最好地定位 Swing GUI?

标签 java swing user-interface

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 上。

Stacked windows on Windows 7 enter image description here Stacked windows on 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/

相关文章:

java - 如果 Swing View 是由 Controller 中的新线程设置的,那么它是否需要同步方法

java - JTree如何知道一个节点已展开但未选择

当我使用 java 标签时,JSP 内的 JavaScript 不起作用

java - 如何访问不同类中的ArrayList

java - 如何在 Maven 中使用共享库组织项目

java - 如何在 Java 中创建从两个变量读取数据的 XY 图表?

java - 如何在 Swing 中使用拖放来获取文件路径?

带行分隔的 Java 列表

ios - 新的 iOS 13 模态演示 : Presenting Controller Doesn't Move Down

performance - 人类可检测到的最小滞后是多少?