package chapter_08.plaf;

import javax.swing.*;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import static java.awt.SystemColor.info;

/**
 * A frame with a button panel for changing look-and-feel
 * @author jerry_0824
 * @version v1.0.0 2016-12-25 9:03
 */
public class PlafFrame extends JFrame {
    private JPanel buttonPanel;

    public PlafFrame() {
        buttonPanel = new JPanel();

        UIManager.LookAndFeelInfo[] infos = UIManager.getInstalledLookAndFeels();
        for (UIManager.LookAndFeelInfo info : infos) {
            makeButton(info.getName(), info.getClassName());
        }

        add(buttonPanel);
        pack();
    }

    /**
     * Makes a button to change the pluggable look-and-feel
     * @param name the button name
     * @param plafName the name of the look-and-feel class
     */
    void makeButton(String name, final String plafName) {
        // add button to panel
        JButton button = new JButton(name);
        buttonPanel.add(button);

        // set button action
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                // button action: switch to the new look-and-feel
                try {
                    UIManager.setLookAndFeel(plafName);
                    SwingUtilities.updateComponentTreeUI(PlafFrame.this);
                    pack();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
