How to change Swing application's look and feel at runtime?

前端 未结 2 1463
礼貌的吻别
礼貌的吻别 2020-12-21 05:54

I know that there\'s a SwingUtilities.updateComponentTreeUI(Component c) method but it doesn\'t work perfectly. For example, I have a JFileChooser

相关标签:
2条回答
  • 2020-12-21 06:35

    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);
    }
    
    0 讨论(0)
  • 2020-12-21 07:00

    Calling SwingUtilities.updateComponentTreeUI(mainWindow) will only update the Swing components in the Swing hierarchy under mainWindow.

    If you store the JFileChooser somewhere in your code (e.g. in a field of a class) without showing the JFileChooser the chooser will not be updated by the SwingUtilities.updateComponentTreeUI(mainWindow) call. You can work around this by adding a listener to the UIManager yourself and call SwingUtilities.updateComponentTreeUI(myStoredFileChooser) from that listener when the look-and-feel is changed.

    Make sure you do not create a memory leak with this, e.g. let that listener only have a WeakReference to the JFileChooser (as the lifetime of the UIManager equals the lifetime of the JVM)

    0 讨论(0)
提交回复
热议问题