Java Swing Menu Item makeCheckboxMenuItem(String label, final Object object, final String property, final Object arg)

Here you can find the source of makeCheckboxMenuItem(String label, final Object object, final String property, final Object arg)

Description

Make a checkbox menu item.

License

Open Source License

Parameter

Parameter Description
label Label
object Object to call
property Name of property to get/set value
arg Optional arg to pass to method

Return

The checkbox

Declaration

public static JCheckBoxMenuItem makeCheckboxMenuItem(String label, final Object object, final String property,
        final Object arg) 

Method Source Code

//package com.java2s;
/*/*from   ww w  . j  a va2  s .  c  o  m*/
 * $Id: GuiUtils.java,v 1.317 2007/08/10 14:26:33 jeffmc Exp $
 *
 * Copyright  1997-2016 Unidata Program Center/University Corporation for
 * Atmospheric Research, P.O. Box 3000, Boulder, CO 80307,
 * support@unidata.ucar.edu.
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or (at
 * your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
 * General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, write to the Free Software Foundation,
 * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

import java.awt.event.*;

import java.lang.reflect.*;
import java.util.ArrayList;

import javax.swing.*;

public class Main {
    /**
     * Make a checkbox menu item. Automatically call the set'property' method on the object
     *
     * @param label Label
     * @param object  Object to call
     * @param property Name of property to get/set value
     * @param arg Optional arg to pass to method
     *
     * @return The checkbox
     */
    public static JCheckBoxMenuItem makeCheckboxMenuItem(String label, final Object object, final String property,
            final Object arg) {

        boolean value = true;
        try {
            String methodName = "get" + property.substring(0, 1).toUpperCase() + property.substring(1);
            Method theMethod = findMethod(object.getClass(), methodName,
                    ((arg == null) ? new Class[] {} : new Class[] { arg.getClass() }));
            if (theMethod != null) {
                Boolean v = (Boolean) theMethod.invoke(object,
                        ((arg == null) ? new Object[] {} : new Object[] { arg }));
                value = v.booleanValue();
            }
        } catch (Exception exc) {
            System.err.println("Error in makeCeckbox:" + exc);
            exc.printStackTrace();
        }
        return makeCheckboxMenuItem(label, object, property, value, arg);
    }

    /**
     * Make a checkbox menu item. Automatically call the set'property' method on the object
     *
     * @param label Label
     * @param object  Object to call
     * @param property Name of property to get/set value
     * @param value The value
     * @param arg Optional arg to pass to method
     *
     * @return The checkbox
     */
    public static JCheckBoxMenuItem makeCheckboxMenuItem(String label, final Object object, final String property,
            boolean value, final Object arg) {

        final JCheckBoxMenuItem cbx = new JCheckBoxMenuItem(label, value);
        ItemListener listener = new ItemListener() {
            public void itemStateChanged(ItemEvent event) {
                try {
                    String methodName = "set" + property.substring(0, 1).toUpperCase() + property.substring(1);
                    Method theMethod = findMethod(object.getClass(), methodName,
                            ((arg == null) ? new Class[] { Boolean.TYPE }
                                    : new Class[] { Boolean.TYPE, arg.getClass() }));
                    if (theMethod == null) {
                        System.err.println("Unknown method:" + object.getClass() + "." + methodName);
                    } else {
                        theMethod.invoke(object, ((arg == null) ? new Object[] { new Boolean(cbx.isSelected()) }
                                : new Object[] { new Boolean(cbx.isSelected()), arg }));
                    }
                } catch (Exception exc) {
                    System.err.println("Error in makeCheckbox:" + exc);
                    exc.printStackTrace();
                }
            }
        };
        cbx.addItemListener(listener);
        return cbx;
    }

    /**
     * Find all methods with the given name.
     * Of these methods find one whose parameter types
     * are assignable from the given parameter types.
     *
     * @param c            class to check
     * @param methodName   name of method
     * @param paramTypes   parameter types
     * @return  class method or <code>null</code> if one doesn't exist
     */
    public static Method findMethod(Class c, String methodName, Class[] paramTypes) {
        ArrayList all = new ArrayList();
        Method[] methods = c.getMethods();
        for (int i = 0; i < methods.length; i++) {
            if (!methodName.equals(methods[i].getName())) {
                continue;
            }
            if (paramTypes == null) {
                return methods[i];
            }
            if (typesMatch(methods[i].getParameterTypes(), paramTypes)) {
                all.add(methods[i]);
            }
        }
        if (all.size() > 1) {
            String msg = "More than one method: " + methodName + " found for class:" + c.getName();
            for (int i = 0; i < paramTypes.length; i++) {
                if (paramTypes[i] != null) {
                    msg += " " + paramTypes[i].getName();
                }
            }
            throw new IllegalArgumentException(msg);
        }
        if (all.size() == 1) {
            return (Method) all.get(0);
        }
        return null;
    }

    /**
     * Find a method
     *
     * @param object     Object with the method in it
     * @param methodName method name
     * @param arg        method argument
     *
     * @return  the method
     */
    private static Method findMethod(Object object, String methodName, Object arg) {

        Method theMethod = null;
        if (arg == null) {
            theMethod = findMethod(object.getClass(), methodName, new Class[] {});
        } else {
            theMethod = findMethod(object.getClass(), methodName, new Class[] { arg.getClass() });
        }
        if (theMethod == null) {
            System.err.println("arg = " + arg);
            throw new IllegalArgumentException("Unknown method:" + object.getClass() + "." + methodName + "("
                    + ((arg == null) ? "" : arg.getClass().getName()) + ")");
        }
        return theMethod;

    }

    /**
     * Returns true if the Classes defined in the actual parameter
     * are equal or a sub-class of the corresponding classes defined in the
     * formal argument.
     *
     * @param formals     formal classes (types)
     * @param actuals     actual classes
     * @return   true  if they match
     */
    public static boolean typesMatch(Class[] formals, Class[] actuals) {
        if (formals.length != actuals.length) {
            return false;
        }
        for (int j = 0; j < formals.length; j++) {
            if (actuals[j] == null) {
                continue;
            }
            if (!formals[j].isAssignableFrom(actuals[j])) {
                return false;
            }
        }
        return true;
    }
}

Related

  1. getTextOffset(JComponent menuItem, Component menuItemParent)
  2. getTexturesMenuItem()
  3. getTopicsMenuItem(ActionListener l)
  4. isSynthUI(final MenuItemUI ui)
  5. loadMenuItem(String action)
  6. makeMenu(String name, List menuItems)
  7. makeMenuItem(Icon icon, Icon rollover, String menu_cmd, boolean is_toggle, int mnemonic, int accel)
  8. makeMenuItem(Icon icon, Icon rollover, String menu_cmd, boolean is_toggle, int mnemonic, int accel)
  9. makeMenuItem(String label, final Object object, final String methodName)