001package jmri.jmrix;
002
003import javax.swing.JMenu;
004import javax.swing.JMenuBar;
005import jmri.jmrix.swing.ComponentFactory;
006import org.slf4j.Logger;
007import org.slf4j.LoggerFactory;
008
009/**
010 * Create a "Systems" menu containing as submenus the JMRI system-specific menus
011 * for available systems.
012 * <p>
013 * Also provides a static member for adding these items to an existing menu.
014 *
015 * @author Bob Jacobsen Copyright 2003
016 */
017public class ActiveSystemsMenu extends JMenu {
018
019    public ActiveSystemsMenu(String name) {
020        this();
021        setText(name);
022        addItems(this);
023    }
024
025    public ActiveSystemsMenu() {
026        super();
027        setText(Bundle.getMessage("MenuSystems"));
028        addItems(this);
029    }
030
031    /**
032     * Add menus for active systems to the menu bar.
033     * @param m the menu bar to add the system menu to.
034     */
035    static public void addItems(JMenuBar m) {
036
037        // get ComponentFactory objects and create menus
038        java.util.List<ComponentFactory> list
039                = jmri.InstanceManager.getList(ComponentFactory.class);
040
041        for (ComponentFactory memo : list) {
042            try {
043                JMenu menu = memo.getMenu();
044                if (menu != null) {
045                    m.add(menu);
046                }
047            } catch (RuntimeException ex) {
048                log.error("Proceeding after error while trying to create menu for {}", memo.getClass(), ex);
049            }
050        }
051    }
052
053    /**
054     * Add active systems as submenus inside a single menu entry.
055     * @param m menu to add the sub menus to.
056     */
057    static public void addItems(JMenu m) {
058
059        // get ComponentFactory objects and create menus
060        java.util.List<ComponentFactory> list
061                = jmri.InstanceManager.getList(ComponentFactory.class);
062
063        for (ComponentFactory memo : list) {
064            JMenu menu = memo.getMenu();
065            if (menu != null) {
066                m.add(menu);
067            }
068        }
069    }
070
071    static JMenu getMenu(String className) {
072        try {
073            return (JMenu) Class.forName(className).getDeclaredConstructor().newInstance();
074        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | java.lang.reflect.InvocationTargetException e) {
075            log.error("Could not load class {}", className, e);
076            return null;
077        }
078    }
079
080    private final static Logger log = LoggerFactory.getLogger(ActiveSystemsMenu.class);
081
082}