// LookAndFeelUtils.java
//
// Created: December 2005
//
// This file is a component of the BioMoby project.
// Copyright Martin Senger (martin.senger@gmail.com).
//

package org.biomoby.service.dashboard;

import javax.swing.UIManager;
import javax.swing.JFrame;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.ButtonGroup;
import javax.swing.JMenu;
import javax.swing.Icon;
import javax.swing.SwingUtilities;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;


/**
 * A utility class helping to set different "Look and Feel"s. <p>
 *
 * @author <A HREF="mailto:martin.senger@gmail.com">Martin Senger</A>
 * @version $Id: LookAndFeelUtils.java,v 1.1 2005/12/18 05:42:23 senger Exp $
 */

public abstract class LookAndFeelUtils {

    /**************************************************************************
     * Create a menu whose sub-menu items - when invoked - change Look
     * and Feel of the whole application (represented by the given
     * 'frame'). <p>
     *
     * It includes all available L-and-Fs in the returning menu but it
     * does not check if all are present. Later when one is selectyed
     * and it is found that its class does not exist, its menu item is
     * disabled. This way saves to load all L-and-Fs in advance. <p>
     *
     * @param title of the created menu
     * @param icon of the created menu (can be null)
     * @param frame is the main application component
     * @return a menu with sub-menus defining available "Look and Feel"s
     **************************************************************************/
    public static JMenu getLookAndFeelMenu (String title,
					    Icon icon,
					    final JFrame frame) {
	UIManager.LookAndFeelInfo[] lafi =
	    UIManager.getInstalledLookAndFeels();
	ButtonGroup lafGroup = new ButtonGroup();
	JMenu options = new JMenu (title);
	options.setIcon (icon);

	for (int i = 0; i < lafi.length; i++) {
	    JRadioButtonMenuItem rb =
		new JRadioButtonMenuItem (lafi [i].getName());
	    options.add (rb);
	    rb.setSelected (UIManager.getLookAndFeel().getName().equals (lafi[i].getName()));
	    rb.putClientProperty ("UIKey", lafi[i]);
	    rb.addItemListener (new ItemListener() {
		    public void itemStateChanged (ItemEvent ae) {
			JRadioButtonMenuItem rb2 = (JRadioButtonMenuItem)ae.getSource();
			if (rb2.isSelected()) {
			    UIManager.LookAndFeelInfo info =
				(UIManager.LookAndFeelInfo)
				rb2.getClientProperty ("UIKey");
			    try {
				UIManager.setLookAndFeel (info.getClassName());
				SwingUtilities.updateComponentTreeUI (frame);
			    } catch (Exception e) {
				rb2.setEnabled (false);
// 				System.err.println ("unable to set UI " + e.getMessage());
			    }
			}
		    }
		});
	    lafGroup.add (rb);
	}
	return options;
    }

}
