create JMenu Item from Action - Java Swing

Java examples for Swing:Action

Description

create JMenu Item from Action

Demo Code


import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.WeakHashMap;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JToolBar;

public class Main{
    public static JMenuItem createMenuItem(Action action) {
        JMenuItem menuItem = new JMenuItem(action);
        JButtonListener listener = new JButtonListener(menuItem);
        action.addPropertyChangeListener(listener);
        configureButton(action, listener);
        return menuItem;
    }//from  ww  w.  j  av a2s  .c  om
    public static void configureButton(Action action,
            PropertyChangeListener listener) {
        if (action == null || listener == null) {
            return;
        }
        action.addPropertyChangeListener(listener);
        action.putValue("listener", listener);
        if (action instanceof AbstractAction) {
            AbstractAction abstractAction = (AbstractAction) action;
            Object[] key = abstractAction.getKeys();
            for (int i = 0; i < key.length; i++) {
                listener.propertyChange(new PropertyChangeEvent(action,
                        key[i].toString(), null, abstractAction
                                .getValue(key[i].toString())));
            }
        }
    }
}

Related Tutorials