Changing LookAndFeel while the application is running

44 Views Asked by At

I wanted to change the LookAndFeel by clicking on the button

public static void main(String[] args) {
    FlatDarculaLaf.setup();

    try {
        UIManager.setLookAndFeel(new FlatDarculaLaf());
    } catch (Exception e) {
        e.printStackTrace();
    }


    JFrame frame = new JFrame("Test");
    frame.setLayout(new FlowLayout());

    JButton b = new JButton("Click");
    b.setSize(10, 5);
    b.addActionListener(e -> {
        FlatLightLaf.setup();
        try {
            UIManager.setLookAndFeel(new FlatLightLaf());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    });

    frame.getContentPane().add(b);

    frame.setVisible(true);
    frame.setBounds(0, 0, 1200, 600);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

but it didn't work. Is there a way to do this, or is it not possible at all?

2

There are 2 best solutions below

1
Grinding For Reputation On BEST ANSWER

Use SwingUtilities.updateComponentTreeUI(frame) after changing the UI to update the UI tree. This should update the frame and all its components

0
Emmanuel Bourg On

If you use FlatLaf (excellent choice!) you can call FlatLaf.updateUI(); after changing the look and feel to update the UI. That's what the FlatLaf demo does to switch look and feels:

https://github.com/JFormDesigner/FlatLaf/blob/61ba011c3ba2404f7e58d324b18cede1e26c6378/flatlaf-demo/src/main/java/com/formdev/flatlaf/demo/ControlBar.java#L226

Without FlatLaf, all the windows have to be updated with:

for (Window window : Window.getWindows()) {
    SwingUtilities.updateComponentTreeUI(window);
}