Example usage for javax.swing JMenuItem getActionListeners

List of usage examples for javax.swing JMenuItem getActionListeners

Introduction

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

Prototype

@BeanProperty(bound = false)
public ActionListener[] getActionListeners() 

Source Link

Document

Returns an array of all the ActionListeners added to this AbstractButton with addActionListener().

Usage

From source file:Main.java

/**
 * Creates a copy of this menu item, whose contents update automatically
 * whenever the original menu item changes.
 *///www. ja v  a  2  s . c  om
public static JMenuItem cloneMenuItem(final JMenuItem item) {
    if (item == null)
        return null;
    JMenuItem jmi;
    if (item instanceof JMenu) {
        final JMenu menu = (JMenu) item;
        final JMenu jm = new JMenu();
        final int count = menu.getItemCount();
        for (int i = 0; i < count; i++) {
            final JMenuItem ijmi = cloneMenuItem(menu.getItem(i));
            if (ijmi == null)
                jm.addSeparator();
            else
                jm.add(ijmi);
        }
        jmi = jm;
    } else
        jmi = new JMenuItem();
    final ActionListener[] l = item.getActionListeners();
    for (int i = 0; i < l.length; i++)
        jmi.addActionListener(l[i]);
    jmi.setActionCommand(item.getActionCommand());
    syncMenuItem(item, jmi);
    linkMenuItem(item, jmi);
    return jmi;
}

From source file:ucar.unidata.idv.control.McVHistogramWrapper.java

/**
 * Add the default menu items/*from   w ww  .j  av  a 2s.c  om*/
 *
 * @param items List of menu items
 *
 * @return The items list
 */
@Override
public List getPopupMenuItems(List items) {
    items = super.getPopupMenuItems(items);
    for (Object o : items) {
        if (o instanceof JMenuItem) {
            JMenuItem menuItem = (JMenuItem) o;
            if ("Properties...".equals(menuItem.getText())) {
                if (menuItem.getActionListeners().length == 0) {
                    menuItem.setActionCommand(ChartPanel.PROPERTIES_COMMAND);
                    menuItem.addActionListener(buildHistoPropsListener());
                }
            }
        }
    }
    return items;
}

From source file:edu.ku.brc.specify.tools.ireportspecify.MainFrameSpecify.java

/**
 * Re maps help links for a couple items on iReport Help menu
 *//*from w w  w.j a v a 2s.  c om*/
public void fixUpHelpLinks() {
    int helpMenuIdx = 9;
    int homePageItemIdx = 0;
    int helpItemIdx = 1;
    final String jasperHomePage = "http://jasperforge.org/";

    JMenuBar mb = getJMenuBar();
    JMenu hm = mb.getMenu(helpMenuIdx);
    homePageItem = hm.getItem(homePageItemIdx);
    //remove original listener linked to bad url
    ActionListener[] als = homePageItem.getActionListeners();
    for (int l = 0; l < als.length; l++) {
        homePageItem.removeActionListener(als[l]);
    }
    //add new listener
    homePageItem.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            openUrl(jasperHomePage);
        }

    });

    JMenuItem helpPageItem = hm.getItem(helpItemIdx);
    als = helpPageItem.getActionListeners();
    //remove original listener linked to bad url
    for (int l = 0; l < als.length; l++) {
        helpPageItem.removeActionListener(als[l]);
    }
    HelpMgr.registerComponent(helpPageItem, "iReport");

    setIconImage(IconManager.getIcon("SPIReports", IconManager.IconSize.NonStd).getImage());

}

From source file:org.eclipse.titanium.graph.gui.windows.GraphEditor.java

/**
 * This method creates the items to show on the {@link Frame} , and adds
 * actions//from w  w  w  .j  a v a  2 s. c  o m
 */
protected void initWindow() {
    drawArea = new JPanel();
    window.add(drawArea, BorderLayout.CENTER);
    drawArea.setSize(windowSize.width, windowSize.height);
    drawArea.setPreferredSize(new Dimension(windowSize.width, windowSize.height));

    menuBar = new JMenuBar();
    window.add(menuBar, BorderLayout.NORTH);

    final JMenu mnFile = new JMenu("File");

    final ActionListener saveGraph = new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            String path = "";
            try {
                path = project.getPersistentProperty(
                        new QualifiedName(ProjectBuildPropertyData.QUALIFIER, "Graph_Save_Path"));
            } catch (CoreException exc) {
                errorHandler.reportException("Error while reading persistent property", exc);
            }
            final String oldPath = path;
            Display.getDefault().asyncExec(new Runnable() {
                @Override
                public void run() {
                    FileDialog dialog = new FileDialog(editorComposite.getShell(), SWT.SAVE);
                    dialog.setText("Save Pajek file");
                    dialog.setFilterPath(oldPath);
                    dialog.setFilterExtensions(new String[] { "*.net", "*.dot" });
                    String graphFilePath = dialog.open();
                    if (graphFilePath == null) {
                        return;
                    }
                    String newPath = graphFilePath.substring(0, graphFilePath.lastIndexOf(File.separator) + 1);
                    try {
                        QualifiedName name = new QualifiedName(ProjectBuildPropertyData.QUALIFIER,
                                "Graph_Save_Path");
                        project.setPersistentProperty(name, newPath);

                        if ("dot".equals(graphFilePath.substring(graphFilePath.lastIndexOf('.') + 1,
                                graphFilePath.length()))) {
                            GraphHandler.saveGraphToDot(graph, graphFilePath, project.getName());
                        } else {
                            GraphHandler.saveGraphToPajek(graph, graphFilePath);
                        }

                    } catch (BadLayoutException be) {
                        ErrorReporter.logExceptionStackTrace("Error while saving image to " + newPath, be);
                        errorHandler.reportErrorMessage("Bad layout\n\n" + be.getMessage());
                    } catch (Exception ce) {
                        ErrorReporter.logExceptionStackTrace("Error while saving image to " + newPath, ce);
                        errorHandler.reportException("Error while setting persistent property", ce);
                    }
                }
            });
        }
    };

    final JMenuItem mntmSave = new JMenuItem("Save (Ctrl+S)");
    mntmSave.addActionListener(saveGraph);
    mnFile.add(mntmSave);

    final ActionListener exportImage = new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            String path = "";
            try {
                path = project.getPersistentProperty(
                        new QualifiedName(ProjectBuildPropertyData.QUALIFIER, "Graph_Save_Path"));
            } catch (CoreException exc) {
                errorHandler.reportException("Error while reading persistent property", exc);
            }
            final String oldPath = path;
            Display.getDefault().asyncExec(new Runnable() {
                @Override
                public void run() {
                    ExportPreferencesDialog prefDialog = new ExportPreferencesDialog(
                            editorComposite.getShell());
                    ImageExportType mode = prefDialog.open();

                    FileDialog dialog = new FileDialog(editorComposite.getShell(), SWT.SAVE);
                    dialog.setText("Export image");
                    dialog.setFilterPath(oldPath);
                    dialog.setFilterExtensions(new String[] { "*.png" });
                    String graphFilePath = dialog.open();
                    if (graphFilePath == null) {
                        return;
                    }
                    String newPath = graphFilePath.substring(0, graphFilePath.lastIndexOf(File.separator) + 1);
                    try {
                        QualifiedName name = new QualifiedName(ProjectBuildPropertyData.QUALIFIER,
                                "Graph_Save_Path");
                        project.setPersistentProperty(name, newPath);
                        handler.saveToImage(graphFilePath, mode);
                    } catch (BadLayoutException be) {
                        errorHandler.reportException("Error while saving image", be);
                        errorHandler.reportErrorMessage(be.getMessage());
                    } catch (CoreException ce) {
                        errorHandler.reportException("Error while setting persistent property", ce);
                    }
                }
            });
        }
    };

    final JMenuItem mntmExportToImage = new JMenuItem("Export to image file (Ctrl+E)");
    mntmExportToImage.addActionListener(exportImage);
    mnFile.add(mntmExportToImage);

    layoutMenu = new JMenu("Layout");
    layoutGroup = new ButtonGroup();

    layoutListener = new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            final IProgressMonitor monitor = Job.getJobManager().createProgressGroup();
            monitor.beginTask("Change layout", 100);
            if (!(e.getSource() instanceof LayoutEntry)) {
                errorHandler.reportErrorMessage(
                        "Unexpected error\n\nAn unusual error has been logged" + LOGENTRYNOTE);
                ErrorReporter.logError("The layout changing event's source is not of type \"LayoutEntry\"!");
                return;
            }
            final LayoutEntry layout = (LayoutEntry) e.getSource();
            if (handler.getVisualizator() != null) {
                drawArea.remove(handler.getVisualizator());
            }
            try {
                handler.changeLayout(layout, windowSize);
                drawArea.add(handler.getVisualizator());
                if (satView != null) {
                    satView.add(handler.getSatelliteViewer());
                }
                window.pack();
            } catch (BadLayoutException exc) {
                layout.setSelected(false);
                chosenLayout.setSelected(true);
                if (exc.getType() == ErrorType.EMPTY_GRAPH || exc.getType() == ErrorType.NO_OBJECT) {
                    return;
                }
                try {
                    handler.changeLayout(chosenLayout, windowSize);
                    drawArea.add(handler.getVisualizator());
                    if (satView != null) {
                        satView.add(handler.getSatelliteViewer());
                    }
                    window.pack();
                    monitor.done();
                } catch (BadLayoutException exc2) {
                    monitor.done();
                    if (exc2.getType() != ErrorType.CYCLIC_GRAPH && exc2.getType() != ErrorType.EMPTY_GRAPH) {
                        errorHandler.reportException("Error while creating layout", exc2);
                    } else {
                        errorHandler.reportErrorMessage(exc2.getMessage());
                    }
                } catch (IllegalStateException exc3) {
                    monitor.done();
                    errorHandler.reportException("Error while creating layout", exc3);
                }
                if (exc.getType() != ErrorType.CYCLIC_GRAPH && exc.getType() != ErrorType.EMPTY_GRAPH) {
                    errorHandler.reportException("Error while creating layout", exc);
                } else {
                    errorHandler.reportErrorMessage(exc.getMessage());
                }
            } catch (IllegalStateException exc) {
                layout.setSelected(false);
                chosenLayout.setSelected(true);
                try {
                    handler.changeLayout(chosenLayout, windowSize);
                    drawArea.add(handler.getVisualizator());
                    if (satView != null) {
                        satView.add(handler.getSatelliteViewer());
                    }
                    window.pack();
                    monitor.done();
                } catch (BadLayoutException exc2) {
                    monitor.done();
                    if (exc2.getType() != ErrorType.CYCLIC_GRAPH && exc2.getType() != ErrorType.EMPTY_GRAPH) {
                        errorHandler.reportException("Error while creating layout", exc2);
                    } else {
                        errorHandler.reportErrorMessage(exc2.getMessage());
                    }
                } catch (IllegalStateException exc3) {
                    monitor.done();
                    errorHandler.reportException("Error while creating layout", exc3);
                }
                errorHandler.reportException("Error while creating layout", exc);
            }
            chosenLayout = layout.newInstance();
            monitor.done();
        }
    };

    final JMenu findMenu = new JMenu("Find");
    final JMenuItem nodeByName = new JMenuItem("Node by name (Ctrl+F)");

    final GraphEditor thisEditor = this;
    nodeByName.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            Display.getDefault().asyncExec(new Runnable() {
                @Override
                public void run() {
                    if (wndFind != null) {
                        wndFind.close();
                    }
                    try {
                        wndFind = new FindWindow<NodeDescriptor>(editorComposite.getShell(), thisEditor,
                                graph.getVertices());
                        wndFind.open();
                    } catch (IllegalArgumentException e) {
                        errorHandler.reportException("", e);
                    }
                }
            });
        }
    });

    findMenu.add(nodeByName);

    final JMenu tools = new JMenu("Tools");
    final JMenuItem findCircles = new JMenuItem("Show circles");
    final JMenuItem findPaths = new JMenuItem("Show parallel paths");
    final JMenuItem clearResults = new JMenuItem("Clear Results");

    findCircles.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent ev) {
            final Job circlesJob = new Job("Searching for circles") {
                @Override
                protected IStatus run(final IProgressMonitor monitor) {
                    if (graph == null) {
                        return null;
                    }
                    CircleCheck<NodeDescriptor, EdgeDescriptor> checker = new CircleCheck<NodeDescriptor, EdgeDescriptor>(
                            graph);
                    if (checker.isCyclic()) {
                        for (EdgeDescriptor e : graph.getEdges()) {
                            e.setColour(Color.lightGray);
                        }
                        for (Deque<EdgeDescriptor> st : checker.getCircles()) {
                            for (EdgeDescriptor e : st) {
                                e.setColour(NodeColours.DARK_RED);
                            }
                        }
                        refresh();
                    } else {
                        errorHandler.reportInformation("Result:\n\nThis graph is not cyclic!");
                    }

                    return Status.OK_STATUS;
                } // end run
            }; // end job
            circlesJob.schedule();
        } // end actionPerformed
    });

    findPaths.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent ev) {
            final Job pathsJob = new Job("Searching for parallel paths") {
                @Override
                protected IStatus run(final IProgressMonitor monitor) {
                    if (graph == null) {
                        return null;
                    }
                    CheckParallelPaths<NodeDescriptor, EdgeDescriptor> checker = null;
                    checker = new CheckParallelPaths<NodeDescriptor, EdgeDescriptor>(graph);
                    if (checker.hasParallelPaths()) {
                        for (EdgeDescriptor e : graph.getEdges()) {
                            e.setColour(Color.lightGray);
                        }
                        for (Deque<EdgeDescriptor> list : checker.getPaths()) {
                            for (EdgeDescriptor e : list) {
                                e.setColour(NodeColours.DARK_RED);
                            }
                        }
                        refresh();
                    } else {
                        errorHandler.reportInformation("Result:\n\nThere are no parallel paths in this graph!");
                    }

                    return Status.OK_STATUS;
                } // end run
            }; // end job
            pathsJob.schedule();
        } // end actionPerformed
    });

    clearResults.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent ev) {
            for (final EdgeDescriptor e : graph.getEdges()) {
                e.setColour(Color.black);
            }
            refresh();
        }
    });

    tools.add(findCircles);
    tools.add(findPaths);
    tools.add(clearResults);

    menuBar.add(mnFile);
    menuBar.add(findMenu);
    menuBar.add(tools);
    menuBar.add(layoutMenu);

    // TODO implement refresh action
    /*
     * JMenuItem RefreshMenu=new JMenuItem("Refresh"); ActionListener
     * RefreshAction=new ActionListener() { public void
     * actionPerformed(ActionEvent ev) { GraphGenerator.schedule(); } };
     * RefreshMenu.addActionListener(RefreshAction);
     * 
     * menuBar.add(RefreshMenu);
     */

    handlerService.activateHandler(GRAPH_SEARCHCMD_ID, new AbstractHandler() {
        @Override
        public Object execute(final ExecutionEvent event) throws ExecutionException {
            nodeByName.getActionListeners()[0].actionPerformed(null);
            handlers.add(this);
            return null;
        }
    });

    handlerService.activateHandler(GRAPH_SAVECMD_ID, new AbstractHandler() {
        @Override
        public Object execute(final ExecutionEvent event) throws ExecutionException {
            mntmSave.getActionListeners()[0].actionPerformed(null);
            handlers.add(this);
            return null;
        }
    });

    handlerService.activateHandler(GRAPH_EXPORTCMD_ID, new AbstractHandler() {
        @Override
        public Object execute(final ExecutionEvent event) throws ExecutionException {
            mntmExportToImage.getActionListeners()[0].actionPerformed(null);
            handlers.add(this);
            return null;
        }
    });

    try {
        generator.generateGraph();
        setLabeller(generator.getLabeler());
        setGraph(generator.getGraph());
    } catch (InterruptedException ex) {
        errorHandler.reportException("Error while creating the graph", ex);
    }

}

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/* w ww. j a va 2s  .com*/
 * 
 * @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.omegat.gui.scripting.ScriptingWindow.java

private void removeAllQuickScriptActionListenersFrom(JMenuItem menu) {
    if (menu == null) {
        return;/*from w w w . j a v a 2s . c  o m*/
    }

    for (ActionListener l : menu.getActionListeners()) {
        if (l instanceof QuickScriptActionListener) {
            menu.removeActionListener(l);
        }
    }
}

From source file:org.openmicroscopy.shoola.env.ui.TaskBarView.java

/**
 * Makes and returns a copy of the specified item.
 *
 * @param original The item to handle.//from  www .  jav a2  s  .  c om
 * @return See above.
 */
private JMenuItem copyItem(JMenuItem original) {
    JMenuItem item = new JMenuItem(original.getAction());
    item.setIcon(original.getIcon());
    item.setText(original.getText());
    item.setToolTipText(original.getToolTipText());
    ActionListener[] al = original.getActionListeners();
    for (int j = 0; j < al.length; j++)
        item.addActionListener(al[j]);
    return item;
}