Example usage for javax.swing JMenuItem setAccelerator

List of usage examples for javax.swing JMenuItem setAccelerator

Introduction

In this page you can find the example usage for javax.swing JMenuItem setAccelerator.

Prototype

@BeanProperty(preferred = true, description = "The keystroke combination which will invoke the JMenuItem's actionlisteners without navigating the menu hierarchy")
public void setAccelerator(KeyStroke keyStroke) 

Source Link

Document

Sets the key combination which invokes the menu item's action listeners without navigating the menu hierarchy.

Usage

From source file:org.geopublishing.atlasStyler.swing.AtlasStylerGUI.java

/**
 * Creates a nre {@link JMenuBar} instance
 *//*  www. j  a va2s  .  com*/
private JMenuBar createMenuBar() {
    JMenuBar jMenuBar = new JMenuBar();

    JMenu fileMenu = new JMenu(AsSwingUtil.R("MenuBar.FileMenu"));

    jMenuBar.add(fileMenu);

    { // Import WIzard
        JMenuItem mi = new JMenuItem(new AbstractAction(AsSwingUtil.R("MenuBar.FileMenu.ImportWizard")) {

            @Override
            public void actionPerformed(ActionEvent e) {
                ImportWizard.showWizard(AtlasStylerGUI.this, AtlasStylerGUI.this);
            }
        });
        mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.CTRL_MASK, true));
        fileMenu.add(mi);
    }

    fileMenu.add(SwingUtil.createChangeLog4JLevelJMenu());

    /**
     * MenuItem to create a new language
     */
    JMenuItem manageLanguageJMenuitem = new JMenuItem(
            new AbstractAction(ASUtil.R("TranslateSoftwareDialog.Title"), Icons.ICON_FLAGS_SMALL) {

                @Override
                public void actionPerformed(ActionEvent e) {
                    String resPath = IOUtil
                            .escapePath(System.getProperty("user.home") + File.separator + ".Geopublishing");
                    ResourceProviderManagerFrame manLanguagesFrame = new ResourceProviderManagerFrame(
                            AtlasStylerGUI.this, true, AsSwingUtil.R("TranslateSoftwareDialog.Explanation.Html",
                                    resPath, SystemUtils.IS_OS_WINDOWS ? "bat" : "sh"));
                    manLanguagesFrame.setRootPath(new File(resPath));
                    manLanguagesFrame.setTitle(ASUtil.R("TranslateSoftwareDialog.Title"));
                    manLanguagesFrame.setPreferredSize(new Dimension(780, 450));
                    manLanguagesFrame.setVisible(true);
                }
            });
    fileMenu.add(manageLanguageJMenuitem);

    AbstractAction optionsButton = new AbstractAction(AtlasStylerVector.R("Options.ButtonLabel")) {

        @Override
        public void actionPerformed(ActionEvent e) {
            new ASOptionsDialog(AtlasStylerGUI.this, AtlasStylerGUI.this);
        }
    };

    fileMenu.add(optionsButton);

    { // Exit
        JMenuItem mi = new JMenuItem(new AbstractAction(
                GpCoreUtil.R("AtlasViewer.FileMenu.ExitMenuItem.exit_application"), Icons.ICON_EXIT_SMALL) {

            @Override
            public void actionPerformed(ActionEvent e) {
                exitAS(0);
            }
        });
        fileMenu.add(mi);
    }

    return jMenuBar;
}

From source file:org.jab.docsearch.DocSearch.java

/**
 * Creates menu bar//from   ww w. j a  v a  2  s.  c o  m
 *
 * @param menuBar  Menu bar
 */
private JMenuBar createMenuBar() {

    // menu bar
    JMenuBar menuBar = new JMenuBar();

    // ----- menu file

    // menu item print
    JMenuItem menuItemPrint = new JMenuItem(I18n.getString("menuitem.print"));
    menuItemPrint.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, Event.CTRL_MASK));
    menuItemPrint.setActionCommand("ac_print");
    menuItemPrint.addActionListener(this);

    // scale X
    JRadioButtonMenuItem scaleXRadioBut = new JRadioButtonMenuItem(I18n.getString("print_scale_width"));
    scaleXRadioBut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, Event.CTRL_MASK));
    scaleXRadioBut.addActionListener(new ScaleXListener());
    // scale Y
    JRadioButtonMenuItem scaleYRadioBut = new JRadioButtonMenuItem(I18n.getString("print_scale_length"));
    scaleYRadioBut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, Event.CTRL_MASK));
    scaleYRadioBut.addActionListener(new ScaleYListener());
    // scale fit
    JRadioButtonMenuItem scaleFitRadioBut = new JRadioButtonMenuItem(I18n.getString("print_scale_to_fit"));
    scaleFitRadioBut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, Event.CTRL_MASK));
    scaleFitRadioBut.addActionListener(new ScaleFitListener());
    // scale half
    JRadioButtonMenuItem scaleHalfRadioBut = new JRadioButtonMenuItem(I18n.getString("print_scale_half"));
    scaleHalfRadioBut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, Event.CTRL_MASK));
    scaleHalfRadioBut.addActionListener(new ScaleHalfListener());
    // scale double
    JRadioButtonMenuItem scale2RadioBut = new JRadioButtonMenuItem(I18n.getString("print_scale_2x"));
    scale2RadioBut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, Event.CTRL_MASK));
    scale2RadioBut.addActionListener(new Scale2Listener());
    // scale off
    JRadioButtonMenuItem scaleOffRadioBut = new JRadioButtonMenuItem(I18n.getString("print_scale_off"), true);
    scaleOffRadioBut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, Event.CTRL_MASK));

    ButtonGroup scaleSetGroup = new ButtonGroup();
    scaleSetGroup.add(scale2RadioBut);
    scaleSetGroup.add(scaleFitRadioBut);
    scaleSetGroup.add(scaleHalfRadioBut);
    scaleSetGroup.add(scaleOffRadioBut);
    scaleSetGroup.add(scaleXRadioBut);
    scaleSetGroup.add(scaleYRadioBut);

    // build complete menu print preferences
    JMenu menuPrintPref = new JMenu(I18n.getString("menuitem.print_preferences"), true);
    menuPrintPref.add(scaleXRadioBut);
    menuPrintPref.add(scaleYRadioBut);
    menuPrintPref.add(scaleFitRadioBut);
    menuPrintPref.add(scaleHalfRadioBut);
    menuPrintPref.add(scale2RadioBut);
    menuPrintPref.addSeparator();
    menuPrintPref.add(scaleOffRadioBut);

    // menu item exit
    JMenuItem menuItemExit = new JMenuItem(I18n.getString("menuitem.exit"));
    menuItemExit.setActionCommand("ac_exit");
    menuItemExit.addActionListener(this);

    // build complete menu file
    JMenu menuFile = new JMenu(I18n.getString("menu.file"));
    menuFile.add(menuItemPrint);
    menuFile.add(menuPrintPref);
    menuFile.addSeparator();
    menuFile.add(menuItemExit);

    // add menu to menu bar
    menuBar.add(menuFile);

    // ----- menu index

    // menu item new
    JMenuItem menuItemNewIndex = new JMenuItem(I18n.getString("menuitem.new_index"));
    menuItemNewIndex.setActionCommand("ac_newindex");
    menuItemNewIndex.addActionListener(this);
    // menu item new spider
    JMenuItem menuItemNewSpiderIndex = new JMenuItem(I18n.getString("menuitem.new_spider_index"));
    menuItemNewSpiderIndex.setActionCommand("ac_newspiderindex");
    menuItemNewSpiderIndex.addActionListener(this);
    // menu item manage
    JMenuItem menuItemManageIndex = new JMenuItem(I18n.getString("menuitem.manage_indexes"));
    menuItemManageIndex.setActionCommand("ac_manageindex");
    menuItemManageIndex.addActionListener(this);
    // menu item rebuild
    JMenuItem menuItemRebuildIndex = new JMenuItem(I18n.getString("menuitem.rebuild_all_indexes"));
    menuItemRebuildIndex.setActionCommand("ac_rebuildindexes");
    menuItemRebuildIndex.addActionListener(this);
    // menu item import
    JMenuItem menuItemImportIndex = new JMenuItem(I18n.getString("menuitem.import_index"));
    menuItemImportIndex.setActionCommand("ac_importindex");
    menuItemImportIndex.addActionListener(this);

    // build complete menu index
    JMenu indexMenu = new JMenu(I18n.getString("menu.index"));
    indexMenu.add(menuItemNewIndex);
    indexMenu.add(menuItemNewSpiderIndex);
    indexMenu.add(menuItemManageIndex);
    indexMenu.add(menuItemRebuildIndex);
    indexMenu.addSeparator();
    indexMenu.add(menuItemImportIndex);

    // add menu to menu bar
    menuBar.add(indexMenu);

    // ----- menu bookmark

    // menu item add
    JMenuItem menuItemAddBookmark = new JMenuItem(I18n.getString("menuitem.add_bookmark"));
    menuItemAddBookmark.setActionCommand("ac_addbookmark");
    menuItemAddBookmark.addActionListener(this);
    // menu item delete all
    JMenuItem menuItemDeleteAll = new JMenuItem(I18n.getString("menuitem.delete_all_bookmarks"));
    menuItemDeleteAll.setActionCommand("ac_deleteallbookmarks");
    menuItemDeleteAll.addActionListener(this);

    // build complete menu index
    bookMarkMenu = new JMenu(I18n.getString("menu.bookmarks"));
    bookMarkMenu.add(menuItemAddBookmark);
    bookMarkMenu.add(menuItemDeleteAll);
    bookMarkMenu.addSeparator();

    // add menu to menu bar
    menuBar.add(bookMarkMenu);

    // ----- menu report

    // menu item metadata report
    JMenuItem menuItemMetadataReport = new JMenuItem(I18n.getString("menuitem.metadata_report"));
    menuItemMetadataReport.setActionCommand("ac_metadata_report");
    menuItemMetadataReport.addActionListener(this);
    // menu item servlet report
    JMenuItem menuItemServletReport = new JMenuItem(I18n.getString("menuitem.servlet_log_report"));
    menuItemServletReport.setActionCommand("ac_servlet_log_report");
    menuItemServletReport.addActionListener(this);

    // build complete menu report
    JMenu reportMenu = new JMenu(I18n.getString("menu.reports"));
    reportMenu.add(menuItemMetadataReport);
    reportMenu.add(menuItemServletReport);

    // add menu to menu bar
    menuBar.add(reportMenu);

    // ----- menu tools

    // menu item makr cd
    JMenuItem menuItemMakeCD = new JMenuItem(I18n.getString("menuitem.make_cd"));
    menuItemMakeCD.setActionCommand("ac_makecd");
    menuItemMakeCD.addActionListener(this);
    // menu item setting
    JMenuItem menuItemSetting = new JMenuItem(I18n.getString("menuitem.settings"));
    menuItemSetting.setActionCommand("ac_settings");
    menuItemSetting.addActionListener(this);

    // build complete menu report
    JMenu menuTool = new JMenu(I18n.getString("menu.tools"));
    menuTool.add(menuItemMakeCD);
    menuTool.addSeparator();
    menuTool.add(menuItemSetting);

    // add menu to menu bar
    menuBar.add(menuTool);

    // ----- menu help

    // menu item search tip
    JMenuItem menuItemSearchTip = new JMenuItem(I18n.getString("menuitem.search_tips"));
    menuItemSearchTip.setActionCommand("ac_search_tips");
    menuItemSearchTip.addActionListener(this);
    // menu item about
    JMenuItem menuItemAbout = new JMenuItem(I18n.getString("menuitem.about"));
    menuItemAbout.setActionCommand("ac_about");
    menuItemAbout.addActionListener(this);

    // build complete menu help
    JMenu menuHelp = new JMenu(I18n.getString("menu.help"));
    menuHelp.add(menuItemSearchTip);
    menuHelp.add(menuItemAbout);

    // add menu to menu bar
    menuBar.add(menuHelp);

    // finished
    return menuBar;
}

From source file:org.jcurl.demo.editor.EditorApp.java

private JMenuItem newMI(final char mnemonic, final int ctrlAccel, final Action action) {
    final JMenuItem item = new JMenuItem(action);
    item.setMnemonic(mnemonic);//from   ww w  .  ja  va2 s.c o m
    if (ctrlAccel >= 0)
        item.setAccelerator(KeyStroke.getKeyStroke(ctrlAccel, InputEvent.CTRL_MASK));
    return item;
}

From source file:org.kepler.gui.KeplerGraphFrame.java

/**
 * Create the menus that are used by this frame. It is essential that
 * _createGraphPane() be called before this.
 *///from  ww w.  jav a2 s .  c  o  m
@Override
protected void _addMenus() {
    super._addMenus();

    // remove Open File... O accelerator.
    // Open... (for KARs) uses this accelerator now.
    for (int i = 0; i < _fileMenuItems.length; i++) {
        JMenuItem menuItem = _fileMenuItems[i];
        if (menuItem != null) {
            String menuItemText = menuItem.getText();
            if (menuItemText != null && menuItemText.equals("Open File")) {
                // int removed =
                // MemoryCleaner.removeActionListeners(menuItem);
                // System.out.println("KeplerGraphFrame _fileMenuItems["+i+"] action listeners removed: "
                // + removed);
                menuItem.setAccelerator(null);
            }
        }
    }

    // see if the effigy for the top level workflow is called "Unnamed"
    // if so, renamed it to "Unnamed1"

    NamedObj namedObj = getModel();
    if (namedObj.getContainer() == null && namedObj.getName().length() == 0) {
        Effigy effigy = getEffigy();
        if (effigy != null) {
            String name = effigy.identifier.getExpression();
            if (name.equals("Unnamed")) {
                String newName = name + _nextUnnamed;
                _nextUnnamed++;
                try {
                    // set the identifier, which is what shows up at the top
                    // of the window
                    effigy.identifier.setExpression(newName);
                } catch (Exception e) {
                    report("Error setting effigy name.", e);
                }

                try {
                    namedObj.setName(newName);
                } catch (Exception e) {
                    report("Error setting workflow name to " + newName + ".", e);
                }

            }
        }
    }

    // let any KeplerGraphFrameUpdaters perform updates.
    Components components = new Components();

    // now call updateFrameComponents on updaters in order
    synchronized (_updaterSet) {
        Iterator<KeplerGraphFrameUpdater> itr = _updaterSet.iterator();
        while (itr.hasNext()) {
            KeplerGraphFrameUpdater updater = itr.next();
            updater.updateFrameComponents(components);
        }
    }

}

From source file:org.nebulaframework.ui.swing.node.NodeMainUI.java

/**
 * Setup Menu Bar/*from  ww w  .ja v  a  2s.  com*/
 * @return JMenu Bar
 */
private JMenuBar setupMenu() {
    JMenuBar menuBar = new JMenuBar();

    /* -- GridNode Menu -- */

    JMenu gridNodeMenu = new JMenu("GridNode");
    gridNodeMenu.setMnemonic(KeyEvent.VK_N);
    menuBar.add(gridNodeMenu);

    // Discover 
    JMenuItem clusterDiscoverItem = new JMenuItem("Disover and Connect Clusters");
    clusterDiscoverItem.setMnemonic(KeyEvent.VK_D);
    clusterDiscoverItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0));
    gridNodeMenu.add(clusterDiscoverItem);
    clusterDiscoverItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            doDiscover(false);
            ((JCheckBoxMenuItem) getUIElement("menu.node.autodiscover")).setSelected(false);
        }
    });
    addUIElement("menu.node.discover", clusterDiscoverItem); // Add to components map

    // Auto-Discovery
    final JCheckBoxMenuItem autodiscoveryItem = new JCheckBoxMenuItem("Auto Discover");
    autodiscoveryItem.setMnemonic(KeyEvent.VK_A);
    autodiscoveryItem.setSelected(true);
    gridNodeMenu.add(autodiscoveryItem);
    autodiscoveryItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            autodiscover = autodiscoveryItem.isSelected();
        }
    });
    addUIElement("menu.node.autodiscover", autodiscoveryItem); // Add to components map

    gridNodeMenu.addSeparator();

    // Cluster-> Shutdown
    JMenuItem nodeShutdownItem = new JMenuItem("Shutdown", 'u');
    nodeShutdownItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0));
    nodeShutdownItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            doShutdownNode();
        }
    });
    gridNodeMenu.add(nodeShutdownItem);
    addUIElement("menu.node.shutdown", nodeShutdownItem); // Add to components map

    /* -- Options Menu -- */
    JMenu optionsMenu = new JMenu("Options");
    optionsMenu.setMnemonic(KeyEvent.VK_O);
    menuBar.add(optionsMenu);

    // Configuration
    JMenuItem optionsConfigItem = new JMenuItem("Configuration...", 'C');
    optionsConfigItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            showConfiguration();
        }
    });
    optionsMenu.add(optionsConfigItem);
    optionsConfigItem.setEnabled(false); // TODO Create Configuration Options

    /* -- Help Menu -- */
    JMenu helpMenu = new JMenu("Help");
    helpMenu.setMnemonic(KeyEvent.VK_H);
    menuBar.add(helpMenu);

    // Help Contents
    JMenuItem helpContentsItem = new JMenuItem("Help Contents", 'H');
    helpContentsItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
    helpContentsItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            showHelp();
        }
    });
    helpMenu.add(helpContentsItem);

    helpMenu.addSeparator();

    JMenuItem helpAboutItem = new JMenuItem("About", 'A');
    helpAboutItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            showAbout();
        }
    });
    helpMenu.add(helpAboutItem);

    return menuBar;
}

From source file:org.omegat.gui.scripting.ScriptingWindow.java

private JMenuBar createMenuBar() {

    mb = new JMenuBar();
    JMenu menu = new JMenu();
    Mnemonics.setLocalizedText(menu, OStrings.getString("SCW_MENU_TITLE"));

    JMenuItem item;

    item = new JMenuItem();
    Mnemonics.setLocalizedText(item, OStrings.getString("SCW_NEW_SCRIPT"));
    item.addActionListener(new NewScriptAction());
    item.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_N, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    menu.add(item);//from  www.  java 2  s .c  o  m

    item = new JMenuItem();
    Mnemonics.setLocalizedText(item, OStrings.getString("SCW_SAVE_SCRIPT"));
    item.addActionListener(new SaveScriptAction());
    item.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    menu.add(item);

    item = new JMenuItem();
    Mnemonics.setLocalizedText(item, OStrings.getString("SCW_RUN_SCRIPT"));
    item.addActionListener(new RunScriptAction());
    item.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_R, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    menu.add(item);

    menu.addSeparator();

    item = new JMenuItem();
    Mnemonics.setLocalizedText(item, OStrings.getString("SCW_MENU_SET_SCRIPTS_FOLDER"));
    item.addActionListener(new SelectScriptFolderAction());
    menu.add(item);

    item = new JMenuItem();
    Mnemonics.setLocalizedText(item, OStrings.getString("SCW_MENU_ACCESS_FOLDER"));
    item.addActionListener(new ExploreScriptFolderAction());
    menu.add(item);

    menu.addSeparator();

    item = new JMenuItem();
    Mnemonics.setLocalizedText(item, OStrings.getString("SCW_MENU_CLOSE"));
    item.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_W, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    item.addActionListener(e -> {
        frame.setVisible(false);
        frame.dispose();
    });
    menu.add(item);

    PropertiesShortcuts.MainMenuShortcuts.bindKeyStrokes(menu);

    mb.add(menu);

    // Edit Menu
    m_txtScriptEditor.enhanceMenu(mb);

    buildSetsMenu(mb);

    return mb;
}

From source file:org.omegat.gui.shortcuts.PropertiesShortcutsTest.java

/**
 * Test of bindKeyStrokes method, of class PropertiesShortcuts.
 *//*from   w w  w.  j  ava 2s  . c o m*/
@Test
public void testBindKeyStrokes_JMenuBar() {
    JMenuBar menu = new JMenuBar();
    JMenu parent = new JMenu();
    JMenuItem child1 = new JMenu();
    JMenuItem child2 = new JMenuItem();
    child2.setActionCommand(TEST_DELETE);
    child2.setAccelerator(CTRL_D);
    JMenuItem grandchild1 = new JMenuItem();
    grandchild1.setActionCommand(TEST_USER_1);
    JMenuItem grandchild2 = new JMenuItem();
    grandchild2.setActionCommand(OUT_OF_LIST);
    grandchild2.setAccelerator(CTRL_X);
    menu.add(parent);
    parent.add(child1);
    parent.add(child2);
    child1.add(grandchild1);
    child1.add(grandchild2);

    // bind
    shotcuts.bindKeyStrokes(menu);

    KeyStroke result = parent.getAccelerator();
    assertNull(result);

    result = child1.getAccelerator();
    assertNull(result);

    result = child2.getAccelerator();
    assertNull(result);

    KeyStroke expected = CTRL_P;
    result = grandchild1.getAccelerator();
    assertEquals(expected, result);

    expected = CTRL_X;
    result = grandchild2.getAccelerator();
    assertEquals(expected, result);
}

From source file:org.omegat.gui.shortcuts.PropertiesShortcutsTest.java

/**
 * Test of bindKeyStrokes method, of class PropertiesShortcuts.
 *///from  ww w .  j a  v  a2  s.  co m
@Test
public void testBindKeyStrokes_JMenuItem() {
    // case JMenuItem with no children
    JMenuItem item = new JMenuItem();
    item.setActionCommand(TEST_SAVE);
    KeyStroke expected = CTRL_S;
    KeyStroke result = item.getAccelerator();
    assertNull(result); // before binding
    shotcuts.bindKeyStrokes(item); // bind
    result = item.getAccelerator();
    assertEquals(expected, result); // after binding(1)

    item.setActionCommand(TEST_DELETE);
    shotcuts.bindKeyStrokes(item); // bind
    result = item.getAccelerator();
    assertNull(result); // after binding(2)

    item.setActionCommand(OUT_OF_LIST);
    item.setAccelerator(CTRL_D);
    shotcuts.bindKeyStrokes(item); // bind
    expected = CTRL_D;
    result = item.getAccelerator();
    assertEquals(expected, result); // after binding(3) - nothing has changed
}

From source file:org.omegat.gui.shortcuts.PropertiesShortcutsTest.java

/**
 * Test of bindKeyStrokes method, of class PropertiesShortcuts.
 *//*  w  ww  . j ava2 s  .c o m*/
@Test
public void testBindKeyStrokes_JMenuItem_Recursive() {
    // case JMenu with children
    JMenu parent = new JMenu();
    JMenuItem child1 = new JMenu();
    JMenuItem child2 = new JMenuItem();
    child2.setActionCommand(TEST_DELETE);
    child2.setAccelerator(CTRL_D);
    JMenuItem grandchild1 = new JMenuItem();
    grandchild1.setActionCommand(TEST_USER_1);
    JMenuItem grandchild2 = new JMenuItem();
    grandchild2.setActionCommand(OUT_OF_LIST);
    grandchild2.setAccelerator(CTRL_X);
    parent.add(child1);
    parent.add(child2);
    child1.add(grandchild1);
    child1.add(grandchild2);

    // bind
    shotcuts.bindKeyStrokes(parent);

    KeyStroke result = parent.getAccelerator();
    assertNull(result);

    result = child1.getAccelerator();
    assertNull(result);

    result = child2.getAccelerator();
    assertNull(result);

    KeyStroke expected = CTRL_P;
    result = grandchild1.getAccelerator();
    assertEquals(expected, result);

    expected = CTRL_X;
    result = grandchild2.getAccelerator();
    assertEquals(expected, result);
}

From source file:org.pmedv.core.provider.ApplicationMenuBarProviderImpl.java

@SuppressWarnings("unused")
public ApplicationMenuBarProviderImpl() {

    populateKeyTable();/* ww  w  .  j av a 2s . co m*/

    menubar = new JMenuBar();

    try {
        JAXBContext c = JAXBContext.newInstance(ApplicationMenubar.class);

        Unmarshaller u = c.createUnmarshaller();

        ApplicationMenubar appMenuBar = (ApplicationMenubar) u
                .unmarshal(getClass().getClassLoader().getResourceAsStream("menus.xml"));

        for (ApplicationMenu currentMenu : appMenuBar.getMenus()) {

            JMenuWithId menu = new JMenuWithId(resources.getResourceByKey(currentMenu.getName()));

            menu.setMnemonic(resources.getResourceByKey(currentMenu.getName()).charAt(0));

            for (ApplicationMenuItem currentItem : currentMenu.getItems()) {

                try {

                    if (currentItem.getActionClass() != null) {

                        if (currentItem.getActionClass().equals("separator")) {
                            menu.addSeparator();
                            continue;
                        }

                        log.info("Mapping action class : " + currentItem.getActionClass());

                        try {

                            AbstractCommand command = null;
                            Class<?> clazz = Class.forName(currentItem.getActionClass());

                            if (currentItem.isBean()) {
                                command = (AbstractCommand) ctx.getBean(clazz);
                            } else {
                                command = (AbstractCommand) clazz.newInstance();
                            }

                            ImageIcon icon = null;
                            String mnemonic = null;
                            String toolTipText = null;

                            if (currentItem.getImageIcon() != null) {

                                InputStream is = getClass().getClassLoader()
                                        .getResourceAsStream(currentItem.getImageIcon());

                                if (is == null) {
                                    is = getClass().getClassLoader()
                                            .getResourceAsStream("icons/noresource_16x16.png");
                                }

                                icon = new ImageIcon(ImageIO.read(is));

                            }
                            if (currentItem.getMnemonic() != null) {
                                mnemonic = currentItem.getMnemonic();
                            }
                            if (currentItem.getToolTipText() != null) {
                                toolTipText = currentItem.getToolTipText();
                            }
                            if (currentItem.getType() != null
                                    && currentItem.getType().equals("ApplicationMenuItemType.CHECKBOX")) {

                                CmdJCheckBoxMenuItem cmdItem = new CmdJCheckBoxMenuItem(currentItem.getName(),
                                        icon, command, mnemonic, toolTipText, null);

                                if (mnemonic != null && currentItem.getModifier() != null) {

                                    if (currentItem.getModifier().equalsIgnoreCase("ctrl")) {
                                        cmdItem.setAccelerator(KeyStroke.getKeyStroke(keyMap.get(mnemonic),
                                                InputEvent.CTRL_MASK, false));
                                    } else if (currentItem.getModifier().equalsIgnoreCase("alt")) {
                                        cmdItem.setAccelerator(KeyStroke.getKeyStroke(keyMap.get(mnemonic),
                                                InputEvent.ALT_MASK, false));
                                    } else if (currentItem.getModifier().equalsIgnoreCase("shift")) {
                                        cmdItem.setAccelerator(KeyStroke.getKeyStroke(keyMap.get(mnemonic),
                                                InputEvent.SHIFT_MASK, false));
                                    }

                                }

                                menu.add(cmdItem);

                            } else {

                                JMenuItem cmdItem = new JMenuItem(command);

                                if (mnemonic != null && currentItem.getModifier() != null) {

                                    if (currentItem.getModifier().equalsIgnoreCase("ctrl")) {
                                        cmdItem.setAccelerator(KeyStroke.getKeyStroke(keyMap.get(mnemonic),
                                                InputEvent.CTRL_MASK, false));
                                    } else if (currentItem.getModifier().equalsIgnoreCase("alt")) {
                                        cmdItem.setAccelerator(KeyStroke.getKeyStroke(keyMap.get(mnemonic),
                                                InputEvent.ALT_MASK, false));
                                    } else if (currentItem.getModifier().equalsIgnoreCase("shift")) {
                                        cmdItem.setAccelerator(KeyStroke.getKeyStroke(keyMap.get(mnemonic),
                                                InputEvent.SHIFT_MASK, false));
                                    }

                                }

                                menu.add(cmdItem);

                            }

                        } catch (InstantiationException e) {
                            log.info("could not instanciate menuitem, skipping.");
                        } catch (IllegalAccessException e) {
                            log.info("could not access menuitem, skipping.");
                        }

                    }

                } catch (ClassNotFoundException e) {
                    log.info("could not find action class " + currentItem.getActionClass());
                }

            }

            if (currentMenu.getType() != null && currentMenu.getType().equalsIgnoreCase("file")) {

                JMenu openRecentMenu = new JMenu(resources.getResourceByKey("menu.recentfiles"));

                RecentFileList fileList = null;

                try {

                    String inputDir = System.getProperty("user.home") + "/." + AppContext.getName() + "/";
                    String inputFileName = "recentFiles.xml";
                    File inputFile = new File(inputDir + inputFileName);

                    if (inputFile.exists()) {
                        Unmarshaller u1 = JAXBContext.newInstance(RecentFileList.class).createUnmarshaller();
                        fileList = (RecentFileList) u1.unmarshal(inputFile);
                    }

                    if (fileList == null)
                        fileList = new RecentFileList();

                    ArrayList<String> recent = fileList.getRecentFiles();
                    Collections.reverse(recent);

                    for (String recentFile : fileList.getRecentFiles()) {
                        File file = new File(recentFile);
                        AbstractCommand openBoardAction = new OpenBoardCommand(file.getName(), file);
                        JMenuItem item = new JMenuItem(openBoardAction);
                        openRecentMenu.add(item);
                    }

                } catch (JAXBException e) {
                    e.printStackTrace();
                }

                menu.addSeparator();
                menu.add(openRecentMenu);

                JMenu openSamplesMenu = createSamplesMenu();

                menu.add(openSamplesMenu);

            }

            menu.setId("common");

            if (currentMenu.getType() != null && !currentMenu.getType().equalsIgnoreCase("help"))
                menubar.add(menu);
            else
                helpMenus.add(menu);

            menubar.setFont(new Font("SansSerif", Font.PLAIN, 12));

        }

        ApplicationPerspectiveProvider perspectiveProvider = ctx.getBean(ApplicationPerspectiveProvider.class);
        ArrayList<ApplicationPerspective> perspectives = perspectiveProvider.getPerspectives();

        JMenuWithId perspectivesMenu = new JMenuWithId("Perspectives");
        perspectivesMenu.setId("common");
        perspectivesMenu.setMnemonic('P');

        for (ApplicationPerspective perspective : perspectives) {

            ImageIcon icon = null;
            String mnemonic = null;
            String toolTipText = null;

            if (perspective.getPerspectiveIcon() != null) {

                InputStream is = getClass().getClassLoader()
                        .getResourceAsStream(perspective.getPerspectiveIcon());

                if (is != null) {
                    icon = new ImageIcon(ImageIO.read(is));
                } else {

                    is = getClass().getClassLoader().getResourceAsStream("icons/noresource_16x16.png");

                    if (is != null)
                        icon = new ImageIcon(ImageIO.read(is));

                }

            }
            if (perspective.getMnemonic() != null) {
                mnemonic = perspective.getMnemonic();
            }
            if (perspective.getToolTipText() != null) {
                toolTipText = perspective.getToolTipText();
            }

            log.info("mapping perspective class " + perspective.getPerspectiveClass());
            OpenPerspectiveCommand command = new OpenPerspectiveCommand(perspective.getId());

            JMenuItem item = new JMenuItem(command);

            if (mnemonic != null && perspective.getModifier() != null) {

                if (perspective.getModifier().equalsIgnoreCase("ctrl")) {
                    item.setAccelerator(
                            KeyStroke.getKeyStroke(keyMap.get(mnemonic), InputEvent.CTRL_MASK, false));
                } else if (perspective.getModifier().equalsIgnoreCase("alt")) {
                    item.setAccelerator(
                            KeyStroke.getKeyStroke(keyMap.get(mnemonic), InputEvent.ALT_MASK, false));
                } else if (perspective.getModifier().equalsIgnoreCase("shift")) {
                    item.setAccelerator(
                            KeyStroke.getKeyStroke(keyMap.get(mnemonic), InputEvent.SHIFT_MASK, false));
                }

            }

            perspectivesMenu.add(item);

            for (ApplicationMenu pMenu : perspective.getMenubarContributions()) {

                JMenuWithId menu = new JMenuWithId(resources.getResourceByKey(pMenu.getName()));

                // if (pMenu.getMnemonic() != null && pMenu.getMnemonic().length() > 0)               
                menu.setMnemonic(resources.getResourceByKey(pMenu.getName()).charAt(0));

                for (ApplicationMenuItem currentItem : pMenu.getItems()) {

                    try {

                        if (currentItem.getActionClass() != null) {

                            if (currentItem.getActionClass().equals("separator")) {
                                menu.addSeparator();
                                continue;
                            }

                            log.info("Mapping action class : " + currentItem.getActionClass());

                            try {

                                AbstractCommand pCommand = null;
                                Class<?> clazz = Class.forName(currentItem.getActionClass());

                                if (currentItem.isBean()) {
                                    pCommand = (AbstractCommand) ctx.getBean(clazz);
                                } else {
                                    pCommand = (AbstractCommand) clazz.newInstance();
                                }

                                ImageIcon pIcon = null;
                                String pMnemonic = null;
                                String pToolTipText = null;

                                if (currentItem.getImageIcon() != null) {

                                    InputStream is = getClass().getClassLoader()
                                            .getResourceAsStream(currentItem.getImageIcon());
                                    pIcon = new ImageIcon(ImageIO.read(is));

                                }
                                if (currentItem.getMnemonic() != null) {
                                    pMnemonic = currentItem.getMnemonic();
                                }
                                if (currentItem.getToolTipText() != null) {
                                    pToolTipText = currentItem.getToolTipText();
                                }

                                if (currentItem.getType() != null
                                        && currentItem.getType().equals("ApplicationMenuItemType.CHECKBOX")) {

                                    log.info(
                                            "Creating menu checkbox for class " + currentItem.getActionClass());

                                    JCheckBoxMenuItem cmdItem = new JCheckBoxMenuItem(pCommand);

                                    if (pMnemonic != null && currentItem.getModifier() != null) {

                                        if (currentItem.getModifier().equalsIgnoreCase("ctrl")) {
                                            cmdItem.setAccelerator(KeyStroke.getKeyStroke(keyMap.get(pMnemonic),
                                                    InputEvent.CTRL_MASK, false));
                                        } else if (currentItem.getModifier().equalsIgnoreCase("alt")) {
                                            cmdItem.setAccelerator(KeyStroke.getKeyStroke(keyMap.get(pMnemonic),
                                                    InputEvent.ALT_MASK, false));
                                        } else if (currentItem.getModifier().equalsIgnoreCase("shift")) {
                                            cmdItem.setAccelerator(KeyStroke.getKeyStroke(keyMap.get(pMnemonic),
                                                    InputEvent.SHIFT_MASK, false));
                                        }

                                    }

                                    menu.add(cmdItem);
                                    cmdItem.setSelected(true);

                                } else {

                                    log.info("Creating menu entry for class " + currentItem.getActionClass());

                                    JMenuItem cmdItem = new JMenuItem(pCommand);

                                    if (pMnemonic != null && currentItem.getModifier() != null) {

                                        if (currentItem.getModifier().equalsIgnoreCase("ctrl")) {
                                            cmdItem.setAccelerator(KeyStroke.getKeyStroke(keyMap.get(pMnemonic),
                                                    InputEvent.CTRL_MASK, false));
                                        } else if (currentItem.getModifier().equalsIgnoreCase("alt")) {
                                            cmdItem.setAccelerator(KeyStroke.getKeyStroke(keyMap.get(pMnemonic),
                                                    InputEvent.ALT_MASK, false));
                                        } else if (currentItem.getModifier().equalsIgnoreCase("shift")) {
                                            cmdItem.setAccelerator(KeyStroke.getKeyStroke(keyMap.get(pMnemonic),
                                                    InputEvent.SHIFT_MASK, false));
                                        }

                                    }

                                    menu.add(cmdItem);

                                }

                            } catch (InstantiationException e) {
                                log.info("could not instanciate menuitem, skipping.");
                            } catch (IllegalAccessException e) {
                                log.info("could not access menuitem, skipping.");
                            }

                        }

                    } catch (ClassNotFoundException e) {
                        log.info("could not find action class " + currentItem.getActionClass());
                    }

                }

                menu.setId(perspective.getId());
                menu.setVisible(false);

                menubar.add(menu);

            }

        }

        if (perspectiveProvider.getPerspectives().size() > 1) {
            menubar.add(perspectivesMenu);
        }

        for (JMenuWithId helpmenu : helpMenus) {
            menubar.add(helpmenu);
        }

        menubar.setFont(new Font("SansSerif", Font.PLAIN, 12));

    } catch (JAXBException e) {
        log.info("could not deserialize menus.");
        throw new RuntimeException("could not deserialize menus.");
    } catch (IOException e) {
        log.info("could not load menus.");
        throw new RuntimeException("could not load menus.");
    }

}