create JButton from Action - Java Swing

Java examples for Swing:Action

Description

create JButton 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 JButton createButton(Action action) {
        JButton button = new JButton(action);
        JButtonListener listener = new JButtonListener(button);
        action.addPropertyChangeListener(listener);
        configureButton(action, listener);
        return button;
    }//from ww  w .  j  a v a2s  . c  o  m
    public static JButton createButton(Object source, String method) {
        Action action = ActionIntrospector.getAction(source, method);
        return createButton(action);
    }
    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