如何在运行时更改Swing应用程序的外观? [英] How to change Swing application's look and feel at runtime?

查看:66
本文介绍了如何在运行时更改Swing应用程序的外观?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有一个 SwingUtilities.updateComponentTreeUI(Component c)方法,但是它不能完美运行.例如,我有一个 JFileChooser ,当前外观是Windows,然后使用 SwingUtilities.updateComponentTreeUI(mainWindow)和main将外观更改为Nimbus.窗口的样式已正确更改,但是当我使用 JFileChooser.showOpenDialog(Component parent)方法显示文件选择器时,它仍然处于Windows外观中.如果显示带有 JPopupMenu.show(Component invoker,int x,int y)方法的弹出对话框,也会发生同样的情况.

I know that there's a SwingUtilities.updateComponentTreeUI(Component c) method but it doesn't work perfectly. For example, I have a JFileChooser and the current look and feel is Windows, then I change the look and feel to Nimbus with SwingUtilities.updateComponentTreeUI(mainWindow), and the main window's style is changed correctly, but when I show the file chooser with the JFileChooser.showOpenDialog(Component parent) method, it's still in Windows look and feel. The same happens if I show a popup dialog with the JPopupMenu.show(Component invoker, int x, int y) method.

对这个问题有什么解决办法吗?

Any solution to this issue?

推荐答案

假定 value 是新外观的类名称,下面是用于更新所有窗口和子窗口的代码段-组件:

Assuming that value is the class name of the new look-and-feel, here is the snippet to update all windows and sub-components:

public static void updateLAF(String value) {
    if (UIManager.getLookAndFeel().getClass().getName().equals(value)) {
        return;
    }
    try {
        UIManager.setLookAndFeel(value);
        for (Frame frame : Frame.getFrames()) {
            updateLAFRecursively(frame);
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedLookAndFeelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public static void updateLAFRecursively(Window window) {
    for (Window childWindow : window.getOwnedWindows()) {
        updateLAFRecursively(childWindow);
    }
    SwingUtilities.updateComponentTreeUI(window);
}

这篇关于如何在运行时更改Swing应用程序的外观?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆