如何在主程序中设置Nimbus外观

5

我正在学习Java,但是仍然无法解决我的小问题。

我的弹出式日历使用Nimbus外观,但是我的面板和容器JTable使用Java的外观 - 我正在尝试使每个GUI屏幕/窗口都使用Nimbus外观。 Merky建议我在主函数中放入以下代码,以使每个后续屏幕都具有Nimbus外观,但我无法使其正常运行,所以我应该在哪里以及如何放置此代码?

public static void main(String args[]) {
    SA md = new OptraderSA("Copyright© 2010 Simon Andi");

    Dimension sd = Toolkit.getDefaultToolkit().getScreenSize();

    md.setLocation(sd.width/2-400/2, sd.height/2-400/2);
    md.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    /*Suggested Code*/
    try {
        for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                UIManager.setLookAndFeel(info.getClassName());
                System.out.println("CHOSEN THIS");
                break;
            } else {
                UIManager.setLookAndFeel  ("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            }
        }
    } catch (Exception e) {
        // If Nimbus is not available, you can set to another look and feel.
        // I can't get it to compile or work.
    }

}
3个回答

13

这是我在主方法中采用的启用Nimbus外观的方式:

public static void main(String[] args) {
    try {
        for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (Exception e) {
        // If Nimbus is not available, fall back to cross-platform
        try {
            UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
        } catch (Exception ex) {
            // Not worth my time
        }
    }
    new Controller();
}

在启动Swing事件分派线程(调用view.setVisible(true)之前),需要确保使用Nimbus外观配置UIManager。


@BenjaminLinus....谢谢!就像你提到的那样,在我开始使用EDT之前必须进行配置。 - user547453

1

我认为可以尝试使用:

for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
    if ("Nimbus".equals(info.getName())) {
        UIManager.setLookAndFeel(info.getClassName());
        System.out.println("CHOSEN THIS");
        break;
    }
}

2
现在我可以看到你的代码了(请在以后使用代码格式),它似乎仅仅做了用户347500展示的,而且比两个月前还要好。:( - Andrew Thompson

1

要设置Nimbus外观,将以下代码添加到您的主方法中:

try {
    for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
            UIManager.setLookAndFeel(info.getClassName());
            break;
        }
    }
} catch (Exception e) {
    e.printStackTrace();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接