Example usage for javax.swing Action isEnabled

List of usage examples for javax.swing Action isEnabled

Introduction

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

Prototype

public boolean isEnabled();

Source Link

Document

Returns the enabled state of the Action .

Usage

From source file:Main.java

public static void main(String args[]) {
    JFrame f = new JFrame();
    Container pane = f.getContentPane();
    Icon icon = new RedOvalIcon();
    final Action action = new MyAction("Hello", icon);
    // Add tooltip
    action.putValue(Action.SHORT_DESCRIPTION, "World");
    JToolBar jt1 = new JToolBar();
    JButton b1 = new JButton(action);
    jt1.add(b1);/*ww  w.  j  a v  a2s. co m*/
    pane.add(jt1, BorderLayout.NORTH);
    JToolBar jt2 = new JToolBar();
    JButton b2 = new JButton(action);
    jt2.add(b2);
    pane.add(jt2, BorderLayout.SOUTH);
    JButton jb = new JButton("Toggle Action");
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            action.setEnabled(!action.isEnabled());
        }
    });
    pane.add(jb, BorderLayout.CENTER);
    f.setSize(200, 200);
    f.show();
}

From source file:Main.java

public static boolean invoke(Action action, Object source) {
    if (action == null || !action.isEnabled()) {
        return false;
    }//www  .  j  av  a 2s .  com
    ActionEvent evt = new ActionEvent(source, ActionEvent.ACTION_PERFORMED,
            (String) action.getValue(Action.ACTION_COMMAND_KEY), 0);
    action.actionPerformed(evt);
    return true;
}

From source file:Main.java

public static void refleshAction(JComponent com, KeyStroke keyStroke) {
    InputMap im = com.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    Object o = im.get(keyStroke);
    if (o == null) {
        im = com.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        o = im.get(keyStroke);/*from   ww w. j a va2s  .c  om*/
    }
    if (o != null) {
        Action a = com.getActionMap().get(o);
        a.setEnabled(a.isEnabled());
    }
}

From source file:de.codesourcery.eve.skills.ui.utils.PopupMenuBuilder.java

protected int populateMenu() {

    int itemCount = 0;
    for (Object obj : this.entries) {
        if (obj == SEPARATOR) {
            popupMenu.addSeparator();/*  w  w  w. j a  v a2s. c  o m*/
        } else {
            final MyMenuItem item = (MyMenuItem) obj;

            final Action action = item.getAction();

            final boolean isEnabled = action.isEnabled();

            if (isEnabled || action instanceof IActionWithDisabledText) {
                final JMenuItem menuItem = new JMenuItem(action);

                final String text;
                if (isEnabled) {
                    text = item.getLabel();
                } else {
                    text = ((IActionWithDisabledText) action).getDisabledText();
                    // do not render action that returns a blank/empty label
                    if (StringUtils.isBlank(text)) {
                        continue;
                    }
                    menuItem.setEnabled(false);
                }
                menuItem.setText(text);
                popupMenu.add(menuItem);
                itemCount++;
            }
        }
    }
    return itemCount;
}

From source file:org.pgptool.gui.ui.keyslist.KeysTableView.java

private void safePerformAction(Action action, ActionEvent event) {
    if (action != null && action.isEnabled()) {
        action.actionPerformed(event);/*from w  w w. ja v  a 2 s  .c om*/
    }
}

From source file:de.tbuchloh.kiskis.gui.MainFrame.java

/**
 * @see de.tbuchloh.kiskis.gui.systray.IMainFrame#getPopupMenu()
 *///  w  w  w .  ja  va  2  s .c  o m
@Override
public PopupMenu getPopupMenu() {
    final PopupMenu popup = new PopupMenu();
    for (final Action act : _main.getPopupActions()) {
        if (act == null) {
            popup.addSeparator();
        } else {
            final MenuItem mi = new MenuItem((String) act.getValue(Action.NAME));
            mi.setEnabled(act.isEnabled());
            mi.addActionListener(act);
            mi.setFont(new Font("Arial", Font.BOLD, 12));
            popup.add(mi);
        }
    }
    return popup;
}

From source file:de.codesourcery.jasm16.ide.ui.MenuManager.java

protected JMenuBar createMenuBar() {
    final List<MenuEntry> copy;
    synchronized (entriesList) {
        copy = new ArrayList<MenuEntry>(entriesList);
    }//from   w  w w  .  j a v  a  2 s  . c  o m

    // collect distinct parent paths
    final List<MenuPath> paths = new ArrayList<MenuPath>();
    for (MenuEntry e : copy) {
        if (!e.isVisible()) {
            continue;
        }
        final MenuPath parentPath = e.getPath().getParentPath();
        if (parentPath == null) {
            continue;
        }
        for (MenuPath p : parentPath.getAllPaths()) {
            if (!paths.contains(p)) {
                paths.add(p);
            }
        }
    }

    // sort paths ascending by length
    Collections.sort(paths, new Comparator<MenuPath>() {

        @Override
        public int compare(MenuPath o1, MenuPath o2) {
            final int len1 = o1.toString().length();
            final int len2 = o2.toString().length();
            if (len1 < len2) {
                return -1;
            } else if (len1 > len2) {
                return 1;
            }
            return 0;
        }
    });

    /*
     * - a
     *   |
     *   +-- b
     *       |
     *       + c  
     */

    // create menu for each path
    final Map<MenuPath, JMenu> menuesByPath = new HashMap<MenuPath, JMenu>();
    for (MenuPath path : paths) {
        final JMenu menu = new JMenu(path.getLastPathComponent());
        menuesByPath.put(path, menu);
        JMenu parentMenu = menuesByPath.get(path.getParentPath());
        if (parentMenu != null) {
            parentMenu.add(menu);
        }
    }

    // setup menu bar

    //Where the GUI is created:
    final JMenuBar menuBar = new JMenuBar();

    final Set<MenuPath> topLevelMenues = new HashSet<MenuPath>();

    for (final MenuEntry e : copy) {

        if (!e.isVisible()) {
            continue;
        }

        final MenuPath parentPath = e.getPath().getParentPath();
        final JMenu menu = menuesByPath.get(parentPath);
        if (menu == null) {
            throw new RuntimeException("Internal error, failed to create menu for path: " + e.getPath());
        }

        // register top-level menues
        if (parentPath.length() == 1) {
            if (!topLevelMenues.contains(parentPath)) {
                menuBar.add(menu);
                topLevelMenues.add(parentPath);
            }
        }

        final Action action;
        action = new AbstractAction(e.getLabel()) {

            @Override
            public void actionPerformed(ActionEvent event) {
                e.onClick();
            }

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

        };

        final JMenuItem item = new JMenuItem(action) {

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

        if (e.hasMnemonic()) {
            item.setMnemonic(e.getMnemonic());
        }
        e.setMenuItem(item);
        menu.add(item);
    }

    return menuBar;
}

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  ww  w. j a v a  2s  .  c  o m*/
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.nuclos.client.common.NuclosCollectController.java

/**
 * @todo this method is misused - it sets shortcuts for many things other than tabs...
 * @param frame//from  w w w.  j a  v  a  2 s .  c om
 */
@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 List<Pair<String[], Action>> getNucletComponentMenuActions(List<GenericAction> genericActions) {
    List<Pair<String[], Action>> nucletComponentMenuAction = new ArrayList<Pair<String[], Action>>();

    final NucletComponentRepository nucletComponentRepository = getNucletComponentRepository();
    if (nucletComponentRepository != null) {
        for (MenuItem mi : nucletComponentRepository.getMenuItems()) {
            if (mi.isEnabled()) {
                String[] menuPath = mi.getMenuPath();
                Action action = mi.getAction();
                // If the component is not allowed to run (due to missing permissions), the action is disabled and skipped
                if (menuPath != null && menuPath.length > 0 && action != null && action.isEnabled()) {
                    nucletComponentMenuAction.add(Pair.makePair(menuPath, action));
                    if (genericActions != null) {
                        WorkspaceDescription.Action wa = new WorkspaceDescription.Action();
                        wa.setAction(GENERIC_NUCLETCOMPONENT_MENUITEM_ACTION);
                        wa.putStringParameter("nucletcomponent.menuitem", mi.getClass().getName());
                        genericActions.add(new GenericAction(wa, new ActionWithMenuPath(menuPath, action)));
                    }//from  w  w  w.j  a  v a 2 s.  c  o m
                }
            }
        }
    }

    return nucletComponentMenuAction;
}