Example usage for javax.swing Action putValue

List of usage examples for javax.swing Action putValue

Introduction

In this page you can find the example usage for javax.swing Action putValue.

Prototype

public void putValue(String key, Object value);

Source Link

Document

Sets one of this object's properties using the associated key.

Usage

From source file:org.apache.log4j.chainsaw.LogUI.java

/**
 * Initialises the Help system and the WelcomePanel
 *
 *///from w  w  w .  ja v  a 2 s  .c  o  m
private void setupHelpSystem() {
    welcomePanel = new WelcomePanel();

    JToolBar tb = welcomePanel.getToolbar();

    tb.add(new SmallButton(new AbstractAction("Tutorial", new ImageIcon(ChainsawIcons.HELP)) {
        public void actionPerformed(ActionEvent e) {
            setupTutorial();
        }
    }));
    tb.addSeparator();

    final Action exampleConfigAction = new AbstractAction("View example Receiver configuration") {
        public void actionPerformed(ActionEvent e) {
            HelpManager.getInstance().setHelpURL(ChainsawConstants.EXAMPLE_CONFIG_URL);
        }
    };

    exampleConfigAction.putValue(Action.SHORT_DESCRIPTION,
            "Displays an example Log4j configuration file with several Receivers defined.");

    JButton exampleButton = new SmallButton(exampleConfigAction);
    tb.add(exampleButton);

    tb.add(Box.createHorizontalGlue());

    /**
     * Setup a listener on the HelpURL property and automatically change the WelcomePages URL
     * to it.
     */
    HelpManager.getInstance().addPropertyChangeListener("helpURL", new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            URL newURL = (URL) evt.getNewValue();

            if (newURL != null) {
                welcomePanel.setURL(newURL);
                ensureWelcomePanelVisible();
            }
        }
    });
}

From source file:org.apache.log4j.chainsaw.LogUI.java

/**
 * Activates itself as a viewer by configuring Size, and location of itself,
 * and configures the default Tabbed Pane elements with the correct layout,
 * table columns, and sets itself viewable.
 *///from  w w  w  .  ja  v  a 2  s .  c om
public void activateViewer() {
    LoggerRepository repo = LogManager.getLoggerRepository();
    if (repo instanceof LoggerRepositoryEx) {
        this.pluginRegistry = ((LoggerRepositoryEx) repo).getPluginRegistry();
    }
    initGUI();

    initPrefModelListeners();

    /**
     * We add a simple appender to the MessageCenter logger
     * so that each message is displayed in the Status bar
     */
    MessageCenter.getInstance().getLogger().addAppender(new AppenderSkeleton() {
        protected void append(LoggingEvent event) {
            getStatusBar().setMessage(event.getMessage().toString());
        }

        public void close() {
        }

        public boolean requiresLayout() {
            return false;
        }
    });

    initSocketConnectionListener();

    if (pluginRegistry.getPlugins(Receiver.class).size() == 0) {
        noReceiversDefined = true;
    }

    getFilterableColumns().add(ChainsawConstants.LEVEL_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.LOGGER_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.THREAD_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.NDC_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.PROPERTIES_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.CLASS_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.METHOD_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.FILE_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.NONE_COL_NAME);

    JPanel panePanel = new JPanel();
    panePanel.setLayout(new BorderLayout(2, 2));

    getContentPane().setLayout(new BorderLayout());

    getTabbedPane().addChangeListener(getToolBarAndMenus());
    getTabbedPane().addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            LogPanel thisLogPanel = getCurrentLogPanel();
            if (thisLogPanel != null) {
                thisLogPanel.updateStatusBar();
            }
        }
    });

    KeyStroke ksRight = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,
            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());
    KeyStroke ksLeft = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,
            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());
    KeyStroke ksGotoLine = KeyStroke.getKeyStroke(KeyEvent.VK_G,
            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());

    getTabbedPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ksRight, "MoveRight");
    getTabbedPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ksLeft, "MoveLeft");
    getTabbedPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ksGotoLine, "GotoLine");

    Action moveRight = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            int temp = getTabbedPane().getSelectedIndex();
            ++temp;

            if (temp != getTabbedPane().getTabCount()) {
                getTabbedPane().setSelectedTab(temp);
            }
        }
    };

    Action moveLeft = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            int temp = getTabbedPane().getSelectedIndex();
            --temp;

            if (temp > -1) {
                getTabbedPane().setSelectedTab(temp);
            }
        }
    };

    Action gotoLine = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            String inputLine = JOptionPane.showInputDialog(LogUI.this, "Enter the line number to go:",
                    "Goto Line", -1);
            try {
                int lineNumber = Integer.parseInt(inputLine);
                int row = getCurrentLogPanel().setSelectedEvent(lineNumber);
                if (row == -1) {
                    JOptionPane.showMessageDialog(LogUI.this, "You have entered an invalid line number",
                            "Error", 0);
                }
            } catch (NumberFormatException nfe) {
                JOptionPane.showMessageDialog(LogUI.this, "You have entered an invalid line number", "Error",
                        0);
            }
        }
    };

    getTabbedPane().getActionMap().put("MoveRight", moveRight);
    getTabbedPane().getActionMap().put("MoveLeft", moveLeft);
    getTabbedPane().getActionMap().put("GotoLine", gotoLine);

    /**
         * We listen for double clicks, and auto-undock currently selected Tab if
         * the mouse event location matches the currently selected tab
         */
    getTabbedPane().addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            super.mouseClicked(e);

            if ((e.getClickCount() > 1) && ((e.getModifiers() & InputEvent.BUTTON1_MASK) > 0)) {
                int tabIndex = getTabbedPane().getSelectedIndex();

                if ((tabIndex != -1) && (tabIndex == getTabbedPane().getSelectedIndex())) {
                    LogPanel logPanel = getCurrentLogPanel();

                    if (logPanel != null) {
                        logPanel.undock();
                    }
                }
            }
        }
    });

    panePanel.add(getTabbedPane());
    addWelcomePanel();

    getContentPane().add(toolbar, BorderLayout.NORTH);
    getContentPane().add(statusBar, BorderLayout.SOUTH);

    mainReceiverSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, panePanel, receiversPanel);
    dividerSize = mainReceiverSplitPane.getDividerSize();
    mainReceiverSplitPane.setDividerLocation(-1);

    getContentPane().add(mainReceiverSplitPane, BorderLayout.CENTER);

    /**
     * We need to make sure that all the internal GUI components have been added to the
     * JFrame so that any plugns that get activated during initPlugins(...) method
     * have access to inject menus  
     */
    initPlugins(pluginRegistry);

    mainReceiverSplitPane.setResizeWeight(1.0);
    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent event) {
            exit();
        }
    });
    preferencesFrame.setTitle("'Application-wide Preferences");
    preferencesFrame.setIconImage(((ImageIcon) ChainsawIcons.ICON_PREFERENCES).getImage());
    preferencesFrame.getContentPane().add(applicationPreferenceModelPanel);

    preferencesFrame.setSize(750, 520);

    Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
    preferencesFrame.setLocation(new Point((screenDimension.width / 2) - (preferencesFrame.getSize().width / 2),
            (screenDimension.height / 2) - (preferencesFrame.getSize().height / 2)));

    pack();

    final JPopupMenu tabPopup = new JPopupMenu();
    final Action hideCurrentTabAction = new AbstractAction("Hide") {
        public void actionPerformed(ActionEvent e) {
            Component selectedComp = getTabbedPane().getSelectedComponent();
            if (selectedComp instanceof LogPanel) {
                displayPanel(getCurrentLogPanel().getIdentifier(), false);
                tbms.stateChange();
            } else {
                getTabbedPane().remove(selectedComp);
            }
        }
    };

    final Action hideOtherTabsAction = new AbstractAction("Hide Others") {
        public void actionPerformed(ActionEvent e) {
            Component selectedComp = getTabbedPane().getSelectedComponent();
            String currentName;
            if (selectedComp instanceof LogPanel) {
                currentName = getCurrentLogPanel().getIdentifier();
            } else if (selectedComp instanceof WelcomePanel) {
                currentName = ChainsawTabbedPane.WELCOME_TAB;
            } else {
                currentName = ChainsawTabbedPane.ZEROCONF;
            }

            int count = getTabbedPane().getTabCount();
            int index = 0;

            for (int i = 0; i < count; i++) {
                String name = getTabbedPane().getTitleAt(index);

                if (getPanelMap().keySet().contains(name) && !name.equals(currentName)) {
                    displayPanel(name, false);
                    tbms.stateChange();
                } else {
                    index++;
                }
            }
        }
    };

    Action showHiddenTabsAction = new AbstractAction("Show All Hidden") {
        public void actionPerformed(ActionEvent e) {
            for (Iterator iter = getPanels().entrySet().iterator(); iter.hasNext();) {
                Map.Entry entry = (Map.Entry) iter.next();
                Boolean docked = (Boolean) entry.getValue();
                if (docked.booleanValue()) {
                    String identifier = (String) entry.getKey();
                    int count = getTabbedPane().getTabCount();
                    boolean found = false;

                    for (int i = 0; i < count; i++) {
                        String name = getTabbedPane().getTitleAt(i);

                        if (name.equals(identifier)) {
                            found = true;

                            break;
                        }
                    }

                    if (!found) {
                        displayPanel(identifier, true);
                        tbms.stateChange();
                    }
                }
            }
        }
    };

    tabPopup.add(hideCurrentTabAction);
    tabPopup.add(hideOtherTabsAction);
    tabPopup.addSeparator();
    tabPopup.add(showHiddenTabsAction);

    final PopupListener tabPopupListener = new PopupListener(tabPopup);
    getTabbedPane().addMouseListener(tabPopupListener);

    this.handler.addPropertyChangeListener("dataRate", new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            double dataRate = ((Double) evt.getNewValue()).doubleValue();
            statusBar.setDataRate(dataRate);
        }
    });

    getSettingsManager().addSettingsListener(this);
    getSettingsManager().addSettingsListener(MRUFileListPreferenceSaver.getInstance());
    getSettingsManager().addSettingsListener(receiversPanel);
    try {
        //if an uncaught exception is thrown, allow the UI to continue to load
        getSettingsManager().loadSettings();
    } catch (Exception e) {
        e.printStackTrace();
    }
    //app preferences have already been loaded (and configuration url possibly set to blank if being overridden)
    //but we need a listener so the settings will be saved on exit (added after loadsettings was called)
    getSettingsManager().addSettingsListener(new ApplicationPreferenceModelSaver(applicationPreferenceModel));

    setVisible(true);

    if (applicationPreferenceModel.isReceivers()) {
        showReceiverPanel();
    } else {
        hideReceiverPanel();
    }

    removeSplash();

    synchronized (initializationLock) {
        isGUIFullyInitialized = true;
        initializationLock.notifyAll();
    }

    if (noReceiversDefined && applicationPreferenceModel.isShowNoReceiverWarning()) {
        SwingHelper.invokeOnEDT(new Runnable() {
            public void run() {
                showReceiverConfigurationPanel();
            }
        });
    }

    Container container = tutorialFrame.getContentPane();
    final JEditorPane tutorialArea = new JEditorPane();
    tutorialArea.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
    tutorialArea.setEditable(false);
    container.setLayout(new BorderLayout());

    try {
        tutorialArea.setPage(ChainsawConstants.TUTORIAL_URL);
        JTextComponentFormatter.applySystemFontAndSize(tutorialArea);

        container.add(new JScrollPane(tutorialArea), BorderLayout.CENTER);
    } catch (Exception e) {
        MessageCenter.getInstance().getLogger().error("Error occurred loading the Tutorial", e);
    }

    tutorialFrame.setIconImage(new ImageIcon(ChainsawIcons.HELP).getImage());
    tutorialFrame.setSize(new Dimension(640, 480));

    final Action startTutorial = new AbstractAction("Start Tutorial",
            new ImageIcon(ChainsawIcons.ICON_RESUME_RECEIVER)) {
        public void actionPerformed(ActionEvent e) {
            if (JOptionPane.showConfirmDialog(null,
                    "This will start 3 \"Generator\" receivers for use in the Tutorial.  Is that ok?",
                    "Confirm", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                new Thread(new Tutorial()).start();
                putValue("TutorialStarted", Boolean.TRUE);
            } else {
                putValue("TutorialStarted", Boolean.FALSE);
            }
        }
    };

    final Action stopTutorial = new AbstractAction("Stop Tutorial",
            new ImageIcon(ChainsawIcons.ICON_STOP_RECEIVER)) {
        public void actionPerformed(ActionEvent e) {
            if (JOptionPane.showConfirmDialog(null,
                    "This will stop all of the \"Generator\" receivers used in the Tutorial, but leave any other Receiver untouched.  Is that ok?",
                    "Confirm", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                new Thread(new Runnable() {
                    public void run() {
                        LoggerRepository repo = LogManager.getLoggerRepository();
                        if (repo instanceof LoggerRepositoryEx) {
                            PluginRegistry pluginRegistry = ((LoggerRepositoryEx) repo).getPluginRegistry();
                            List list = pluginRegistry.getPlugins(Generator.class);

                            for (Iterator iter = list.iterator(); iter.hasNext();) {
                                Plugin plugin = (Plugin) iter.next();
                                pluginRegistry.stopPlugin(plugin.getName());
                            }
                        }
                    }
                }).start();
                setEnabled(false);
                startTutorial.putValue("TutorialStarted", Boolean.FALSE);
            }
        }
    };

    stopTutorial.putValue(Action.SHORT_DESCRIPTION,
            "Removes all of the Tutorials Generator Receivers, leaving all other Receivers untouched");
    startTutorial.putValue(Action.SHORT_DESCRIPTION,
            "Begins the Tutorial, starting up some Generator Receivers so you can see Chainsaw in action");
    stopTutorial.setEnabled(false);

    final SmallToggleButton startButton = new SmallToggleButton(startTutorial);
    PropertyChangeListener pcl = new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            stopTutorial.setEnabled(((Boolean) startTutorial.getValue("TutorialStarted")).equals(Boolean.TRUE));
            startButton.setSelected(stopTutorial.isEnabled());
        }
    };

    startTutorial.addPropertyChangeListener(pcl);
    stopTutorial.addPropertyChangeListener(pcl);

    pluginRegistry.addPluginListener(new PluginListener() {
        public void pluginStarted(PluginEvent e) {
        }

        public void pluginStopped(PluginEvent e) {
            List list = pluginRegistry.getPlugins(Generator.class);

            if (list.size() == 0) {
                startTutorial.putValue("TutorialStarted", Boolean.FALSE);
            }
        }
    });

    final SmallButton stopButton = new SmallButton(stopTutorial);

    final JToolBar tutorialToolbar = new JToolBar();
    tutorialToolbar.setFloatable(false);
    tutorialToolbar.add(startButton);
    tutorialToolbar.add(stopButton);
    container.add(tutorialToolbar, BorderLayout.NORTH);
    tutorialArea.addHyperlinkListener(new HyperlinkListener() {
        public void hyperlinkUpdate(HyperlinkEvent e) {
            if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                if (e.getDescription().equals("StartTutorial")) {
                    startTutorial.actionPerformed(null);
                } else if (e.getDescription().equals("StopTutorial")) {
                    stopTutorial.actionPerformed(null);
                } else {
                    try {
                        tutorialArea.setPage(e.getURL());
                    } catch (IOException e1) {
                        MessageCenter.getInstance().getLogger()
                                .error("Failed to change the URL for the Tutorial", e1);
                    }
                }
            }
        }
    });

    /**
     * loads the saved tab settings and if there are hidden tabs,
     * hide those tabs out of currently loaded tabs..
     */

    if (!getTabbedPane().tabSetting.isWelcome()) {
        displayPanel(ChainsawTabbedPane.WELCOME_TAB, false);
    }
    if (!getTabbedPane().tabSetting.isZeroconf()) {
        displayPanel(ChainsawTabbedPane.ZEROCONF, false);
    }
    tbms.stateChange();

}

From source file:org.jcurl.demo.tactics.old.ActionRegistry.java

/** Create a disabled {@link Action}. */
private Action createAction(final Object controller, final Method m, final JCAction a) {
    final Action ac = new AbstractAction() {
        private static final long serialVersionUID = 2349356576661476730L;

        public void actionPerformed(final ActionEvent e) {
            try {
                m.invoke(controller, (Object[]) null);
            } catch (final IllegalArgumentException e1) {
                throw new RuntimeException("Unhandled", e1);
            } catch (final IllegalAccessException e1) {
                throw new RuntimeException("Unhandled", e1);
            } catch (final InvocationTargetException e1) {
                throw new RuntimeException("Unhandled", e1);
            }/*www.  ja  v  a  2  s.c om*/
        }
    };
    ac.putValue(Action.NAME, stripMnemonic(a.title()));
    ac.putValue(Action.ACCELERATOR_KEY, findAccelerator(a.accelerator()));
    if (false) {
        final Character mne = findMnemonic(a.title());
        if (mne != null)
            ac.putValue(Action.MNEMONIC_KEY, KeyStroke.getKeyStroke(mne));
    }
    ac.setEnabled(false);
    return ac;
}

From source file:org.jivesoftware.sparkimpl.plugin.viewer.PluginViewer.java

public void initialize() {
    // Add Plugins Menu
    JMenuBar menuBar = SparkManager.getMainWindow().getJMenuBar();

    // Get last menu which is help
    JMenu sparkMenu = menuBar.getMenu(0);

    JMenuItem viewPluginsMenu = new JMenuItem();

    Action viewAction = new AbstractAction() {
        private static final long serialVersionUID = 6518407602062984752L;

        public void actionPerformed(ActionEvent e) {
            invokeViewer();//ww  w.  j  a v a  2 s  .  co  m
        }
    };

    viewAction.putValue(Action.NAME, Res.getString("menuitem.plugins"));
    viewAction.putValue(Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.PLUGIN_IMAGE));
    viewPluginsMenu.setAction(viewAction);

    sparkMenu.insert(viewPluginsMenu, 2);
}

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

/**
 * Recurse through all the submenu heirarchy beneath the passed JMenu
 * parameter, and for each "leaf node" (ie a menu item that is not a
 * container for other menu items), add the Action and its menu path to the
 * passed Map/*from  www .  ja v a2  s. co m*/
 * 
 * @param nextMenuItem
 *            the JMenu to recurse into
 * @param menuPathBuff
 *            a delimited String representation of the hierarchical "path"
 *            to this menu item. This will be used as the key in the
 *            actionsMap. For example, the "Graph Editor" menu item beneath
 *            the "New" item on the "File" menu would have a menuPath of
 *            File->New->Graph Editor. Delimeter is "->" (no quotes), and
 *            spaces are allowed within menu text strings, but not around
 *            the delimiters; i.e: New->Graph Editor is OK, but File ->New
 *            is not.
 * @param MENU_PATH_DELIMITER
 *            String
 * @param actionsMap
 *            the Map containing key => value pairs of the form: menuPath
 *            (as described above) => Action (the javax.swing.Action
 *            assigned to this menu item)
 */
public static void storePTIIMenuItems(JMenuItem nextMenuItem, StringBuffer menuPathBuff,
        final String MENU_PATH_DELIMITER, Map<String, Action> actionsMap) {

    menuPathBuff.append(MENU_PATH_DELIMITER);
    if (nextMenuItem != null && nextMenuItem.getText() != null) {
        String str = nextMenuItem.getText();
        // do not make the recent files menu item upper case since
        // it contains paths in the file system.
        if (menuPathBuff.toString().startsWith("FILE->RECENT FILES->")) {
            menuPathBuff = new StringBuffer("File->Recent Files->");
        } else {
            str = str.toUpperCase();
        }
        menuPathBuff.append(str);
    }

    if (isDebugging) {
        log.debug(menuPathBuff.toString());
    }
    // System.out.println(menuPathBuff.toString());

    if (nextMenuItem instanceof JMenu) {
        storePTIITopLevelMenus((JMenu) nextMenuItem, menuPathBuff.toString(), MENU_PATH_DELIMITER, actionsMap);
    } else {
        Action nextAction = nextMenuItem.getAction();
        // if there is no Action, look for an ActionListener
        // System.out.println("Processing menu " + nextMenuItem.getText());
        if (nextAction == null) {
            final ActionListener[] actionListeners = nextMenuItem.getActionListeners();
            // System.out.println("No Action for " + nextMenuItem.getText()
            // + "; found " + actionListeners.length
            // + " ActionListeners");
            if (actionListeners.length > 0) {
                if (isDebugging) {
                    log.debug(actionListeners[0].getClass().getName());
                }
                // ASSUMPTION: there is only one ActionListener
                nextAction = new AbstractAction() {
                    public void actionPerformed(ActionEvent a) {
                        actionListeners[0].actionPerformed(a);
                    }
                };
                // add all these values - @see diva.gui.GUIUtilities
                nextAction.putValue(Action.NAME, nextMenuItem.getText());
                // System.out.println("storing ptII action for menu " +
                // nextMenuItem.getText());
                nextAction.putValue(GUIUtilities.LARGE_ICON, nextMenuItem.getIcon());
                nextAction.putValue(GUIUtilities.MNEMONIC_KEY, new Integer(nextMenuItem.getMnemonic()));
                nextAction.putValue("tooltip", nextMenuItem.getToolTipText());
                nextAction.putValue(GUIUtilities.ACCELERATOR_KEY, nextMenuItem.getAccelerator());
                nextAction.putValue("menuItem", nextMenuItem);
            } else {
                if (isDebugging) {
                    log.warn("No Action or ActionListener found for " + nextMenuItem.getText());
                }
            }
        }
        if (!actionsMap.containsValue(nextAction)) {
            actionsMap.put(menuPathBuff.toString(), nextAction);
            if (isDebugging) {
                log.debug(menuPathBuff.toString() + " :: ACTION: " + nextAction);
            }
        }
    }
}

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

public static JMenuItem addMenuFor(String key, Action action, JComponent topLvlContainer,
        Map<String, JMenuItem> keplerMenuMap) {

    if (topLvlContainer == null) {
        if (isDebugging) {
            log.debug("NULL container received (eg JMenuBar) - returning NULL");
        }//w ww .  j  a  va2  s  .  com
        return null;
    }
    if (key == null) {
        if (isDebugging) {
            log.debug("NULL key received");
        }
        return null;
    }
    key = key.trim();

    if (key.length() < 1) {
        if (isDebugging) {
            log.debug("BLANK key received");
        }
        return null;
    }
    if (action == null && key.indexOf(MENU_SEPARATOR_KEY) < 0) {
        if (isDebugging) {
            log.debug("NULL action received, but was not a separator: " + key);
        }
        return null;
    }

    if (keplerMenuMap.containsKey(key)) {
        if (isDebugging) {
            log.debug("Menu already added; skipping: " + key);
        }
        return null;
    }

    // split delimited parts and ensure menus all exist
    String[] menuLevel = key.split(MENU_PATH_DELIMITER);

    int totLevels = menuLevel.length;

    // create a menu for each "menuLevel" if it doesn't already exist
    final StringBuffer nextLevelBuff = new StringBuffer();
    String prevLevelStr = null;
    JMenuItem leafMenuItem = null;

    for (int levelIdx = 0; levelIdx < totLevels; levelIdx++) {

        // save previous value
        prevLevelStr = nextLevelBuff.toString();

        String nextLevelStr = menuLevel[levelIdx];
        // get the index of the first MNEMONIC_SYMBOL
        int mnemonicIdx = nextLevelStr.indexOf(MNEMONIC_SYMBOL);
        char mnemonicChar = 0;

        // if an MNEMONIC_SYMBOL exists, remove all underscores. Then, idx
        // of
        // first underscore becomes idx of letter it used to precede - this
        // is the mnemonic letter
        if (mnemonicIdx > -1) {
            nextLevelStr = nextLevelStr.replaceAll(MNEMONIC_SYMBOL, "");
            mnemonicChar = nextLevelStr.charAt(mnemonicIdx);
        }
        if (levelIdx != 0) {
            nextLevelBuff.append(MENU_PATH_DELIMITER);
        }
        nextLevelBuff.append(nextLevelStr);

        // don't add multiple separators together...
        if (nextLevelStr.indexOf(MENU_SEPARATOR_KEY) > -1) {
            if (separatorJustAdded == false) {

                // Check if we're at the top level, since this makes sense
                // only for
                // context menu - we can't add a separator to a JMenuBar
                if (levelIdx == 0) {
                    if (topLvlContainer instanceof JContextMenu) {
                        ((JContextMenu) topLvlContainer).addSeparator();
                    }
                } else {
                    JMenu parent = (JMenu) keplerMenuMap.get(prevLevelStr);

                    if (parent != null) {
                        if (parent.getMenuComponentCount() < 1) {
                            if (isDebugging) {
                                log.debug("------ NOT adding separator to parent " + parent.getText()
                                        + ", since it does not contain any menu items");
                            }
                        } else {
                            if (isDebugging) {
                                log.debug("------ adding separator to parent " + parent.getText());
                            }
                            // add separator to parent
                            parent.addSeparator();
                            separatorJustAdded = true;
                        }
                    }
                }
            }
        } else if (!keplerMenuMap.containsKey(nextLevelBuff.toString())) {
            // If menu has not already been created, we need
            // to create it and then add it to the parent level...

            JMenuItem menuItem = null;

            // if we're at a "leaf node" - need to create a JMenuItem
            if (levelIdx == totLevels - 1) {

                // save old display name to use as actionCommand on
                // menuitem,
                // since some parts of PTII still
                // use "if (actionCommand.equals("SaveAs")) {..." etc
                String oldDisplayName = (String) action.getValue(Action.NAME);

                // action.putValue(Action.NAME, nextLevelStr);

                if (mnemonicChar > 0) {
                    action.putValue(GUIUtilities.MNEMONIC_KEY, new Integer(mnemonicChar));
                }

                // Now we look to see if it's a checkbox
                // menu item, or just a regular one
                String menuItemType = (String) (action.getValue(MENUITEM_TYPE));

                if (menuItemType != null && menuItemType == CHECKBOX_MENUITEM_TYPE) {
                    menuItem = new JCheckBoxMenuItem(action);
                } else {
                    menuItem = new JMenuItem(action);
                }

                // --------------------------------------------------------------
                /** @todo - setting menu names - TEMPORARY FIX - FIXME */
                // Currently, if we use the "proper" way of setting menu
                // names -
                // ie by using action.putValue(Action.NAME, "somename");,
                // then
                // the name appears on the port buttons on the toolbar,
                // making
                // them huge. As a temporary stop-gap, I am just setting the
                // new
                // display name using setText() instead of
                // action.putValue(..,
                // but this needs to be fixed elsewhere - we want to be able
                // to
                // use action.putValue(Action.NAME (ie uncomment the line
                // above
                // that reads:
                // action.putValue(Action.NAME, nextLevelStr);
                // and delete the line below that reads:
                // menuItem.setText(nextLevelStr);
                // otherwise this may bite us in future...
                menuItem.setText(nextLevelStr);
                // --------------------------------------------------------------

                // set old display name as actionCommand on
                // menuitem, for ptii backward-compatibility
                menuItem.setActionCommand(oldDisplayName);

                // add JMenuItem to the Action, so it can be accessed by
                // Action code
                action.putValue(NEW_JMENUITEM_KEY, menuItem);
                leafMenuItem = menuItem;
            } else {
                // if we're *not* at a "leaf node" - need to create a JMenu
                menuItem = new JMenu(nextLevelStr);
                if (mnemonicChar > 0) {
                    menuItem.setMnemonic(mnemonicChar);
                }
            }
            // level 0 is a special case, since the container (JMenuBar or
            // JContextMenu) is not a JMenu or a JMenuItem, so we can't
            // use the same code to add child to parent...
            if (levelIdx == 0) {
                if (topLvlContainer instanceof JMenuBar) {
                    // this handles JMenuBar menus
                    ((JMenuBar) topLvlContainer).add(menuItem);
                } else if (topLvlContainer instanceof JContextMenu) {
                    // this handles popup context menus
                    ((JContextMenu) topLvlContainer).add(menuItem);
                }
                // add to Map
                keplerMenuMap.put(nextLevelBuff.toString(), menuItem);
                separatorJustAdded = false;
            } else {
                JMenu parent = (JMenu) keplerMenuMap.get(prevLevelStr);
                if (parent != null) {
                    // add to parent
                    parent.add(menuItem);
                    // add to Map
                    keplerMenuMap.put(nextLevelBuff.toString(), menuItem);
                    separatorJustAdded = false;
                } else {
                    if (isDebugging) {
                        log.debug("Parent menu is NULL" + prevLevelStr);
                    }
                }
            }
        }
    }
    return leafMenuItem;
}

From source file:org.languagetool.gui.Main.java

private JMenuBar createMenuBar() {
    JMenuBar menuBar = new JMenuBar();
    JMenu fileMenu = new JMenu(getLabel("guiMenuFile"));
    fileMenu.setMnemonic(getMnemonic("guiMenuFile"));
    JMenu editMenu = new JMenu(getLabel("guiMenuEdit"));
    editMenu.setMnemonic(getMnemonic("guiMenuEdit"));
    JMenu grammarMenu = new JMenu(getLabel("guiMenuGrammar"));
    grammarMenu.setMnemonic(getMnemonic("guiMenuGrammar"));
    JMenu helpMenu = new JMenu(getLabel("guiMenuHelp"));
    helpMenu.setMnemonic(getMnemonic("guiMenuHelp"));

    fileMenu.add(openAction);//from   w w w .ja  v a2s  .co m
    fileMenu.add(saveAction);
    fileMenu.add(saveAsAction);
    recentFilesMenu = new JMenu(getLabel("guiMenuRecentFiles"));
    recentFilesMenu.setMnemonic(getMnemonic("guiMenuRecentFiles"));
    fileMenu.add(recentFilesMenu);
    updateRecentFilesMenu();
    fileMenu.addSeparator();
    fileMenu.add(new HideAction());
    fileMenu.addSeparator();
    fileMenu.add(new QuitAction());

    grammarMenu.add(checkAction);
    JCheckBoxMenuItem item = new JCheckBoxMenuItem(autoCheckAction);
    grammarMenu.add(item);
    JCheckBoxMenuItem showResult = new JCheckBoxMenuItem(showResultAction);
    grammarMenu.add(showResult);
    grammarMenu.add(new CheckClipboardAction());
    grammarMenu.add(new TagTextAction());
    grammarMenu.add(new AddRulesAction());
    grammarMenu.add(new OptionsAction());
    grammarMenu.add(new SelectFontAction());
    JMenu lafMenu = new JMenu(messages.getString("guiLookAndFeelMenu"));
    UIManager.LookAndFeelInfo[] lafInfo = UIManager.getInstalledLookAndFeels();
    ButtonGroup buttonGroup = new ButtonGroup();
    for (UIManager.LookAndFeelInfo laf : lafInfo) {
        if (!"Nimbus".equals(laf.getName())) {
            continue;
        }
        addLookAndFeelMenuItem(lafMenu, laf, buttonGroup);
    }
    for (UIManager.LookAndFeelInfo laf : lafInfo) {
        if ("Nimbus".equals(laf.getName())) {
            continue;
        }
        addLookAndFeelMenuItem(lafMenu, laf, buttonGroup);
    }
    grammarMenu.add(lafMenu);

    helpMenu.add(new AboutAction());

    undoRedo.undoAction.putValue(Action.NAME, getLabel("guiMenuUndo"));
    undoRedo.undoAction.putValue(Action.MNEMONIC_KEY, getMnemonic("guiMenuUndo"));
    undoRedo.redoAction.putValue(Action.NAME, getLabel("guiMenuRedo"));
    undoRedo.redoAction.putValue(Action.MNEMONIC_KEY, getMnemonic("guiMenuRedo"));

    editMenu.add(undoRedo.undoAction);
    editMenu.add(undoRedo.redoAction);
    editMenu.addSeparator();

    Action cutAction = new DefaultEditorKit.CutAction();
    cutAction.putValue(Action.SMALL_ICON, getImageIcon("sc_cut.png"));
    cutAction.putValue(Action.LARGE_ICON_KEY, getImageIcon("lc_cut.png"));
    cutAction.putValue(Action.NAME, getLabel("guiMenuCut"));
    cutAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_T);
    editMenu.add(cutAction);

    Action copyAction = new DefaultEditorKit.CopyAction();
    copyAction.putValue(Action.SMALL_ICON, getImageIcon("sc_copy.png"));
    copyAction.putValue(Action.LARGE_ICON_KEY, getImageIcon("lc_copy.png"));
    copyAction.putValue(Action.NAME, getLabel("guiMenuCopy"));
    copyAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_C);
    editMenu.add(copyAction);

    Action pasteAction = new DefaultEditorKit.PasteAction();
    pasteAction.putValue(Action.SMALL_ICON, getImageIcon("sc_paste.png"));
    pasteAction.putValue(Action.LARGE_ICON_KEY, getImageIcon("lc_paste.png"));
    pasteAction.putValue(Action.NAME, getLabel("guiMenuPaste"));
    pasteAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_P);
    editMenu.add(pasteAction);

    editMenu.addSeparator();

    editMenu.add(new SelectAllAction());

    menuBar.add(fileMenu);
    menuBar.add(editMenu);
    menuBar.add(grammarMenu);
    menuBar.add(helpMenu);
    return menuBar;
}

From source file:org.nuclos.client.common.NuclosCollectController.java

/**
 * @todo this method is misused - it sets shortcuts for many things other than tabs...
 * @param frame//  ww  w. ja  v a2 s. c o  m
 */
@Override
protected void setupShortcutsForTabs(MainFrameTab frame) {
    final CollectPanel<Clct> pnlCollect = this.getCollectPanel();
    final DetailsPanel pnlDetails = this.getDetailsPanel();

    final Action actSelectSearchTab = new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent ev) {
            if (pnlCollect.isTabbedPaneEnabledAt(CollectPanel.TAB_SEARCH)) {
                pnlCollect.setTabbedPaneSelectedComponent(getSearchPanel());
            }
        }
    };
    KeyBindingProvider.bindActionToComponent(KeyBindingProvider.ACTIVATE_SEARCH_PANEL_1, actSelectSearchTab,
            pnlCollect);
    KeyBindingProvider.bindActionToComponent(KeyBindingProvider.ACTIVATE_SEARCH_PANEL_2, actSelectSearchTab,
            pnlCollect);

    //TODO This is a workaround. The detailpanel should keep the focus
    final Action actGrabFocus = new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent ev) {
            pnlDetails.grabFocus();
        }
    };

    /**
     * A <code>ChainedAction</code> is an action composed of a primary and a secondary action.
     * It behaves exactly like the primary action, except that additionally, the secondary action is performed
     * after the primary action.
     */
    class ChainedAction implements Action {
        private final Action actPrimary;
        private final Action actSecondary;

        public ChainedAction(Action actPrimary, Action actSecondary) {
            this.actPrimary = actPrimary;
            this.actSecondary = actSecondary;
        }

        @Override
        public void addPropertyChangeListener(PropertyChangeListener listener) {
            actPrimary.addPropertyChangeListener(listener);
        }

        @Override
        public Object getValue(String sKey) {
            return actPrimary.getValue(sKey);
        }

        @Override
        public boolean isEnabled() {
            return actPrimary.isEnabled();
        }

        @Override
        public void putValue(String sKey, Object oValue) {
            actPrimary.putValue(sKey, oValue);
        }

        @Override
        public void removePropertyChangeListener(PropertyChangeListener listener) {
            actPrimary.removePropertyChangeListener(listener);
        }

        @Override
        public void setEnabled(boolean bEnabled) {
            actPrimary.setEnabled(bEnabled);
        }

        @Override
        public void actionPerformed(ActionEvent ev) {
            actPrimary.actionPerformed(ev);
            actSecondary.actionPerformed(ev);
        }
    }

    //final Action actRefresh = new ChainedAction(this.getRefreshCurrentCollectableAction(), actGrabFocus);

    this.getCollectPanel().setTabbedPaneToolTipTextAt(CollectPanel.TAB_SEARCH,
            getSpringLocaleDelegate().getMessage("NuclosCollectController.13", "Suche (F7) (Strg+F)"));
    this.getCollectPanel().setTabbedPaneToolTipTextAt(CollectPanel.TAB_RESULT,
            getSpringLocaleDelegate().getMessage("NuclosCollectController.7", "Ergebnis (F8)"));
    this.getCollectPanel().setTabbedPaneToolTipTextAt(CollectPanel.TAB_DETAILS,
            getSpringLocaleDelegate().getMessage("NuclosCollectController.3", "Details (F2)"));

    // the search action
    KeyBindingProvider.bindActionToComponent(KeyBindingProvider.START_SEARCH, this.getSearchAction(),
            pnlCollect);
    KeyBinding keybinding = KeyBindingProvider.REFRESH;

    // the refresh action
    KeyBindingProvider.removeActionFromComponent(keybinding, pnlDetails);
    pnlDetails.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(keybinding.getKeystroke(),
            keybinding.getKey());
    pnlDetails.getActionMap().put(keybinding.getKey(), this.getRefreshCurrentCollectableAction());
    KeyBindingProvider.removeActionFromComponent(keybinding, getResultPanel());
    getResultPanel().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(keybinding.getKeystroke(),
            keybinding.getKey());
    getResultPanel().getActionMap().put(keybinding.getKey(), getResultPanel().btnRefresh.getAction());

    // the new action
    KeyBindingProvider.bindActionToComponent(KeyBindingProvider.NEW, this.getNewAction(), pnlDetails);

    // the new with search values action
    KeyBindingProvider.bindActionToComponent(KeyBindingProvider.NEW_SEARCHVALUE,
            this.getNewWithSearchValuesAction(), pnlCollect);

    // the save action
    KeyBindingProvider.bindActionToComponent(KeyBindingProvider.SAVE_1, this.getSaveAction(), pnlCollect);
    KeyBindingProvider.bindActionToComponent(KeyBindingProvider.SAVE_2, this.getSaveAction(), pnlCollect);

    // first the navigation actions are performed and then the focus is grabbed:
    final Action actFirst = new ChainedAction(this.getFirstAction(), actGrabFocus);
    final Action actLast = new ChainedAction(this.getLastAction(), actGrabFocus);
    final Action actPrevious = new ChainedAction(this.getPreviousAction(), actGrabFocus);
    final Action actNext = new ChainedAction(this.getNextAction(), actGrabFocus);

    // the first action
    KeyBindingProvider.bindActionToComponent(KeyBindingProvider.FIRST, actFirst, pnlDetails);
    pnlDetails.btnFirst.setAction(actFirst);

    // the last action
    KeyBindingProvider.bindActionToComponent(KeyBindingProvider.LAST, actLast, pnlDetails);
    pnlDetails.btnLast.setAction(actLast);

    // the previous action
    KeyBindingProvider.bindActionToComponent(KeyBindingProvider.PREVIOUS_1, actPrevious, pnlDetails);
    KeyBindingProvider.bindActionToComponent(KeyBindingProvider.PREVIOUS_2, actPrevious, pnlDetails);
    pnlDetails.btnPrevious.setAction(actPrevious);

    // the next action
    KeyBindingProvider.bindActionToComponent(KeyBindingProvider.NEXT_1, actNext, pnlDetails);
    KeyBindingProvider.bindActionToComponent(KeyBindingProvider.NEXT_2, actNext, pnlDetails);
    pnlDetails.btnNext.setAction(actNext);

    Action actClose = new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            getTab().dispose();
        }
    };
    KeyBindingProvider.bindActionToComponent(KeyBindingProvider.CLOSE_CHILD, actClose, pnlCollect);

    if (getResultPanel() != null && getResultTable() != null) {
        final JButton btnEdit = getResultPanel().btnEdit;
        KeyBindingProvider.bindActionToComponent(KeyBindingProvider.EDIT_1, btnEdit.getAction(),
                getResultTable());
        if (getResultTable().getActionMap().get(KeyBindingProvider.EDIT_2.getKey()) == null)
            KeyBindingProvider.bindActionToComponent(KeyBindingProvider.EDIT_2, btnEdit.getAction(),
                    getResultTable());
    }
}

From source file:org.nuclos.client.main.MainController.java

private Action createEntityAction(EntityMetaDataVO entitymetavo, String label, final boolean isNew,
        final Long processId, final String customUsage) {
    String entity = entitymetavo.getEntity();
    if (!getSecurityCache().isReadAllowedForEntity(entity)) {
        return null;
    }// ww w .j  a v  a  2  s  .co  m

    if (isNew && entitymetavo.isStateModel()
            && !getSecurityCache().isNewAllowedForModuleAndProcess(IdUtils.unsafeToId(entitymetavo.getId()),
                    IdUtils.unsafeToId(processId))) {
        return null;
    }

    Action action = new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent evt) {
            cmdCollectMasterData(evt, isNew, processId, customUsage);
        }
    };
    Pair<String, Character> nameAndMnemonic = MenuGenerator.getMnemonic(label);
    action.putValue(Action.NAME,
            customUsage == null ? nameAndMnemonic.x : String.format("%s (%s)", nameAndMnemonic.x, customUsage));
    if (nameAndMnemonic.y != null) {
        action.putValue(Action.MNEMONIC_KEY, (int) nameAndMnemonic.y.charValue());
    }
    action.setEnabled(true);
    action.putValue(Action.SMALL_ICON,
            MainFrame.resizeAndCacheTabIcon(Main.getInstance().getMainFrame().getEntityIcon(entity)));
    action.putValue(Action.ACTION_COMMAND_KEY, entity);
    if (!isNew && processId == null) {
        if (!StringUtils.isNullOrEmpty(entitymetavo.getAccelerator())
                && entitymetavo.getAcceleratorModifier() != null) {
            int keycode = entitymetavo.getAccelerator().charAt(0);
            if (keycode > 90)
                keycode -= 32;

            action.putValue(Action.ACCELERATOR_KEY,
                    KeyStroke.getKeyStroke(keycode, entitymetavo.getAcceleratorModifier().intValue()));
        } else if (!StringUtils.isNullOrEmpty(entitymetavo.getAccelerator())) {
            action.putValue(Action.ACCELERATOR_KEY,
                    KeyStroke.getKeyStroke(entitymetavo.getAccelerator().charAt(0)));
        }
    }

    return action;
}

From source file:org.openconcerto.task.TodoListPanel.java

void initPopUp() {
    TablePopupMouseListener.add(this.t, new ITransformer<MouseEvent, JPopupMenu>() {

        @Override/*from ww w .j av a2  s .  com*/
        public JPopupMenu transformChecked(MouseEvent evt) {
            final JTable table = (JTable) evt.getSource();
            final int modelIndex = TodoListPanel.this.sorter.modelIndex(table.getSelectedRow());
            final JPopupMenu res = new JPopupMenu();

            // Avancer d'un jour
            Action act = new AbstractAction() {
                public void actionPerformed(ActionEvent e) {
                    final TodoListElement element = TodoListPanel.this.model.getTaskAtRow(modelIndex);
                    if (element != null) {
                        final Date ts = element.getExpectedDate();
                        final Calendar cal = Calendar.getInstance();
                        cal.setTimeInMillis(ts.getTime());
                        cal.add(Calendar.DAY_OF_YEAR, 1);
                        SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                ts.setTime(cal.getTimeInMillis());
                                element.setExpectedDate(ts);
                                element.commitChangesAndWait();
                                table.repaint();
                            }
                        });
                    }
                }
            };
            act.putValue(Action.NAME, TM.tr("moveOneDay"));
            res.add(act);

            // Marquer comme ralis
            act = new AbstractAction() {
                public void actionPerformed(ActionEvent e) {
                    TodoListElement element = TodoListPanel.this.model.getTaskAtRow(modelIndex);
                    if (element != null) {
                        element.setDone(true);
                        element.commitChangesAndWait();
                        table.repaint();
                    }
                }
            };
            act.putValue(Action.NAME, TM.tr("markDone"));
            res.add(act);

            // Suppression
            act = new AbstractAction() {
                public void actionPerformed(ActionEvent e) {
                    TodoListPanel.this.model.deleteTaskAtIndex(modelIndex);
                    table.repaint();
                }
            };
            act.putValue(Action.NAME, TM.tr("delete"));
            res.add(act);

            final TodoListElement element = TodoListPanel.this.model.getTaskAtRow(modelIndex);
            SQLRowValues rowTache = element.getRowValues();

            List<AbstractAction> actions = TacheActionManager.getInstance().getActionsForTaskRow(rowTache);

            for (AbstractAction abstractAction : actions) {
                res.add(abstractAction);
            }

            return res;
        }
    });
}