如何在运行时改变swing应用程序的外观和感觉?

Zha*_* Yi 2 java user-interface swing look-and-feel

我知道有一种SwingUtilities.updateComponentTreeUI(Component c)方法,但它不能很好地工作.例如,我有一个JFileChooser当前的外观和感觉是Windows,然后我将外观改为Nimbus SwingUtilities.updateComponentTreeUI(mainWindow),并且主窗口的样式已正确更改,但是当我用该JFileChooser.showOpenDialog(Component parent)方法显示文件选择器时,它仍然在Windows中外观和感觉.如果我使用该JPopupMenu.show(Component invoker, int x, int y)方法显示弹出对话框,也会发生同样的情况.解决这个问题的任何方法?

Gui*_*let 6

假设这value是新外观的类名,这里是更新所有窗口和子组件的片段:

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);
}
Run Code Online (Sandbox Code Playgroud)


Rob*_*bin 5

调用SwingUtilities.updateComponentTreeUI(mainWindow)只会更新Swing层次结构中的Swing组件mainWindow.

如果您将JFileChooser代码存储在代码中(例如,在类的字段中)而不显示JFileChooser选择器将不会被SwingUtilities.updateComponentTreeUI(mainWindow)调用更新.您可以通过向UIManager自己添加侦听器并SwingUtilities.updateComponentTreeUI(myStoredFileChooser)在外观更改时从该侦听器调用来解决此问题.

确保你没有创建与此内存泄漏,如让那听众只有一个WeakReferenceJFileChooser(如UIManager的寿命等于JVM的寿命)