Updating the LAF of a different class

2019-09-12 15:43发布

问题:

In a "Battleship" program I wrote, I included the possibility to change the "look and feel" of a program to SystemDefault, "Metal" (Java Default) or "Motif" (also included in Java). If you choose the desired LAF from a JComboBox (--> changes a predefined String, lookFeel) and press a confirm button, UIManager.setLookAndFeel(lookFeel) is called, and also SwingUtilities.updateComponentTreeUI(this) and the method updateUI() with the following code:

public static void updateUI() {
        //SwingUtilities.updateComponentTreeUI();
        SwingUtilities.updateComponentTreeUI(colorChooser);
        SwingUtilities.updateComponentTreeUI(shipChooser);
        SwingUtilities.updateComponentTreeUI(guide);
        SwingUtilities.updateComponentTreeUI(menu_bar);
        SwingUtilities.updateComponentTreeUI(menu_general);
        SwingUtilities.updateComponentTreeUI(menu_customization);
        SwingUtilities.updateComponentTreeUI(lafChooser);

        SwingUtilities.updateComponentTreeUI(LAN.lanframe);
        SwingUtilities.updateComponentTreeUI(LAN.hostframe);
        SwingUtilities.updateComponentTreeUI(LAN.joinframe);
    }

However, this code will not update other windows that are part of a different class. Hence, if I launch my main program, and then change the look&feel, these windows won't be affected. Those classes that actually create a frame are not a problem, but my main program just extends JFrame (something I probably wouldn't do again, but I was entirely new to Java when I started writing this program). Now my question is: how can I change the LAF of this class? Thanks in advance!

回答1:

If the result of getSupportsWindowDecorations() is true for a given LookAndFeel, you can invoke setWindowDecorationStyle() on the JRootPane. A complete example is cited here in UIManager Defaults.



回答2:

See How to change swing applicaiton's look and feel at runtime? on how to call updateComponentTreeUI on all windows of your application.

Note that the updateComponentTreeUI will recursively update all subcomponents, therefore you don't need to call it for each and every component, rather call it for all the windows (frames).