Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.util.Arrays;

import java.util.List;

import javax.swing.Action;
import javax.swing.ActionMap;

import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;

import javax.swing.JMenu;

import javax.swing.JMenuItem;

public class Main {
    /**
     * Creates a {@link JMenu} from the given list and action map.
     * 
     * @param actionMap
     * @param list
     * @return
     */
    public static JMenu createMenu(ActionMap actionMap, List<?> list) {
        // The first item will be the action for the JMenu
        final Action titleAction = actionMap.get(list.get(0));
        if (titleAction == null) {
            return null;
        }
        final JMenu menu = new JMenu();
        menu.setAction(titleAction);

        // The rest of the items represent the menu items.
        for (Object element : list.subList(1, list.size())) {
            if (element == null) {
                menu.addSeparator();
            } else if (element instanceof List<?>) {
                JMenu newMenu = createMenu(actionMap, (List<?>) element);
                if (newMenu != null) {
                    menu.add(newMenu);
                }
            } else if (element.getClass().isArray()) {
                JMenu newMenu = createMenu(actionMap, (Object[]) element);
                if (newMenu != null) {
                    menu.add(newMenu);
                }
            } else {
                final Action action = actionMap.get(element);
                if (action == null) {
                    continue;
                } else {
                    menu.add(createMenuItem(action));
                }
            }
        }
        return menu;
    }

    /**
     * Creates a {@link JMenu} from the given array and action map.
     * 
     * @param actionMap
     * @param keys
     * @return
     * @see #createMenu(ActionMap, List)
     */
    public static JMenu createMenu(ActionMap actionMap, Object... array) {
        return createMenu(actionMap, Arrays.asList(array));
    }

    /**
     * Creates a suitable menu item.
     * 
     * @param action
     * @return
     */
    public static JMenuItem createMenuItem(Action action) {
        final JMenuItem mi;
        final Boolean selected = (Boolean) action.getValue(Action.SELECTED_KEY);
        if (selected != null) {
            mi = new JCheckBoxMenuItem(action);
        } else {
            mi = new JMenuItem(action);
        }
        mi.setHorizontalTextPosition(JButton.TRAILING);
        mi.setVerticalTextPosition(JButton.CENTER);
        return mi;
    }
}