import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.*;

import javax.swing.*;


/**
 * @author Remi Forax
 *
 */
public class MenuExample3 {

  private static Method getSetter(Object bean,String property,Class type) throws NoSuchMethodException {
    String setterName="set"+Character.toUpperCase(property.charAt(0))+property.substring(1);
    return bean.getClass().getMethod(setterName,new Class[]{type});
  }

  private static JMenu createColorMenu(final JComponent component,String title,String property) 
    throws NoSuchMethodException {
      
    JMenu menu=new JMenu(title);
    ButtonGroup group=new ButtonGroup();
    
    final Method method=getSetter(component,property,Color.class);
    
    Field[] fields=Color.class.getFields();
    for(int i=0;i<fields.length;i++) {
      final Field field=fields[i];
      String name=field.getName();
      if (Character.isUpperCase(name.charAt(0))) {
        JCheckBoxMenuItem item=new JCheckBoxMenuItem(name.toLowerCase());
        item.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            try {
              method.invoke(component,new Object[]{
                field.get(null)});
            } catch (Exception e) {
              JOptionPane.showMessageDialog(component, e, "Erreur", 
                JOptionPane.ERROR_MESSAGE);
            }
          }
        });
        menu.add(item);
        group.add(item);
      }
    }
    
    return menu;
  }

  public static void main(String[] args) throws NoSuchMethodException {
    
    JMenu edit=new JMenu("Edit");
    
    JButton button=new JButton("Hello Menu");
    edit.add(createColorMenu(button,"couleur d'arrière plan","background"));
    edit.add(createColorMenu(button,"couleur d'avant plan","foreground"));
    
    JPanel panel=new JPanel();
    panel.add(button);
    
    JMenuBar bar=new JMenuBar();
    bar.add(edit);
    
    JFrame frame=new JFrame();
    frame.setJMenuBar(bar);
    frame.setContentPane(panel);
    frame.setSize(400,300);
    frame.show();
  }
}
