Example usage for javax.swing JMenuItem getText

List of usage examples for javax.swing JMenuItem getText

Introduction

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

Prototype

public String getText() 

Source Link

Document

Returns the button's text.

Usage

From source file:nz.govt.natlib.ndha.manualdeposit.ManualDepositPresenterTest.java

@Test
public final void testFavourites() {
    LOG.debug("*************************************************************************");
    LOG.debug("testFavourites");
    LOG.debug("*************************************************************************");
    // Set it up//from  w w  w.j  a  v a 2s . co  m
    FileUtils.deleteFileOrDirectoryRecursive(FAVOURITES_PATH);
    try {
        setUp();
    } catch (Exception ex) {
        fail();
    }
    DepositTreeModel fileSystemModel = (DepositTreeModel) theFrame.treeFileSystem.getModel();
    DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) fileSystemModel.getRoot();
    FSOCollection coll = FSOCollection.create();
    FileSystemObject fso = (FileSystemObject) rootNode.getUserObject();
    coll.add(fso);
    if (fso.getFile() == null) {
        LOG.debug("Root Object (file null): " + fso.getDescription());
    } else {
        try {
            LOG.debug("Root Object (file not null): " + fso.getFile().getCanonicalPath());
        } catch (Exception ex) {
        }
    }
    for (int i = 0; i < rootNode.getChildCount(); i++) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) rootNode.getChildAt(i);
        fso = (FileSystemObject) node.getUserObject();
        if (fso.getFile() == null) {
            LOG.debug("Child " + i + " (file null): " + fso.getDescription());
        } else {
            try {
                LOG.debug("Child " + i + " (file not null): " + fso.getFile().getCanonicalPath());
            } catch (Exception ex) {
            }
        }
    }
    File settingsPathFile = new File(RESOURCES_SETTINGS_PATH);
    File favouritesPathFile = new File(FAVOURITES_PATH);
    assertTrue(favouritesPathFile.exists());
    FileSystemObject child = null;
    // Make sure the tree includes the path
    String fullPath = "";
    try {
        fullPath = settingsPathFile.getCanonicalPath();
    } catch (Exception ex) {
        fail();
    }
    String[] paths;
    String fileSeparator = System.getProperty("file.separator");
    if (fileSeparator.equals("\\")) {
        fullPath = fullPath.replaceAll("/", fileSeparator);
        paths = fullPath.split("[\\\\]");
    } else {
        fullPath = fullPath.replaceAll("[\\\\]", fileSeparator);
        paths = fullPath.split(fileSeparator);
    }
    String currentPath = "";
    String rootPath = paths[0] + fileSeparator;
    LOG.debug("Full Path: " + fullPath);
    LOG.debug("Root Path: " + rootPath);
    for (int i = 0; i < paths.length; i++) {
        LOG.debug("Path " + i + ": " + paths[i]);
    }
    for (int i = 0; i < paths.length; i++) {
        currentPath += paths[i] + fileSeparator;
        LOG.debug("Current Path: " + currentPath);
        child = coll.getFSOByFullPath(currentPath, true);
        if (child == null) {
            LOG.debug("Child is null (not found)");
        } else {
            if (child.getFile() == null) {
                LOG.debug("Child found, file is null");
            } else {
                LOG.debug("Child found, path " + child.getFullPath());
            }
        }
        depositPresenter.selectNode(child, ETreeType.FileSystemTree);
        TreePath currentTreePath = theFrame.treeFileSystem.getSelectionPath();
        LOG.debug("currentTreePath: " + currentTreePath.toString());
        depositPresenter.expandFileSystemTree(currentTreePath);
    }

    // Test the favourites
    // No favourites loaded - check that the menu is empty
    TreePath[] treePaths = null;
    depositPresenter.clearFavourites();
    assertFalse(depositPresenter.canStoreFavourites(treePaths));
    treePaths = theFrame.treeFileSystem.getSelectionPaths();
    assertTrue(depositPresenter.canStoreFavourites(treePaths));
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) theFrame.treeFileSystem
            .getLastSelectedPathComponent();
    fso = (FileSystemObject) node.getUserObject();
    JPopupMenu menu = (JPopupMenu) theFrame.mnuFileFavourites.getSubElements()[0];
    assertTrue(menu.getSubElements().length == 1);
    JMenuItem item = (JMenuItem) menu.getSubElements()[0];
    String noFavouritesText = item.getText();
    assertFalse(noFavouritesText.equals(fso.getFullPath()));

    // Store a favourite & check that it is included in the menu
    depositPresenter.storeAsFavourite(node);
    assertTrue(menu.getSubElements().length == 2);
    item = (JMenuItem) menu.getSubElements()[0];
    assertTrue(item.getText().equals(fso.getFullPath()));
    // Reset the screen & then check that the favourite is included in the
    // menu
    try {
        setUp();
    } catch (Exception ex) {
        fail();
    }
    menu = (JPopupMenu) theFrame.mnuFileFavourites.getSubElements()[0];
    assertTrue(menu.getSubElements().length == 2);
    item = (JMenuItem) menu.getSubElements()[0];
    assertTrue(item.getText().equals(fso.getFullPath()));
    // Delete the storage file & make sure that there are no menu items
    FileUtils.deleteFileOrDirectoryRecursive(FAVOURITES_PATH);
    try {
        setUp();
    } catch (Exception ex) {
        fail();
    }
    menu = (JPopupMenu) theFrame.mnuFileFavourites.getSubElements()[0];
    assertTrue(menu.getSubElements().length == 1);
    item = (JMenuItem) menu.getSubElements()[0];
    assertTrue(item.getText().equals(noFavouritesText));

    // Check clearing
    depositPresenter.storeAsFavourite(node);
    assertTrue(menu.getSubElements().length == 2);
    item = (JMenuItem) menu.getSubElements()[0];
    assertTrue(item.getText().equals(fso.getFullPath()));
    depositPresenter.clearFavourites();
    assertTrue(theFrame.mnuFileFavourites.getSubElements().length == 1);
    item = (JMenuItem) menu.getSubElements()[0];
    assertTrue(item.getText().equals(noFavouritesText));

    // Check loading a directory
    fileSystemModel = (DepositTreeModel) theFrame.treeFileSystem.getModel();
    rootNode = (DefaultMutableTreeNode) fileSystemModel.getRoot();
    coll = FSOCollection.create();
    coll.add((FileSystemObject) rootNode.getUserObject());
    currentPath = rootPath;
    depositPresenter.loadPath(currentPath);
    DefaultMutableTreeNode newNode = (DefaultMutableTreeNode) theFrame.treeFileSystem
            .getLastSelectedPathComponent();
    FileSystemObject fsoNew = (FileSystemObject) newNode.getUserObject();
    assertTrue(fsoNew.getFullPath().equals(currentPath));
    currentPath = fso.getFullPath();
    depositPresenter.loadPath(currentPath);
    newNode = (DefaultMutableTreeNode) theFrame.treeFileSystem.getLastSelectedPathComponent();
    fsoNew = (FileSystemObject) newNode.getUserObject();
    assertTrue(fsoNew.getFullPath().equals(fso.getFullPath()));
    FileUtils.deleteFileOrDirectoryRecursive(FAVOURITES_PATH);
}

From source file:org.esa.snap.graphbuilder.rcp.dialogs.support.GraphPanel.java

private static JMenu getMenuFolder(final String folderName, final JMenu currentMenu) {
    int insertPnt = 0;
    for (int i = 0; i < currentMenu.getItemCount(); ++i) {
        JMenuItem item = currentMenu.getItem(i);
        if (item instanceof JMenu) {
            int comp = item.getText().compareToIgnoreCase(folderName);
            if (comp == 0) {
                return (JMenu) item;
            } else if (comp < 0) {
                insertPnt++;// w  w  w. jav a  2 s .c om
            }
        }
    }

    final JMenu newMenu = new JMenu(folderName);
    newMenu.setIcon(folderIcon);
    currentMenu.insert(newMenu, insertPnt);
    return newMenu;
}

From source file:org.eurocarbdb.application.glycoworkbench.plugin.s3.Cockpit.java

/**
 * Logs out of the S3 service by clearing all listed objects and buckets and resetting
 * the s3ServiceMulti member variable.//from ww  w .  j  a  v  a 2  s .co  m
 *
 * This method should always be invoked within the event dispatching thread.
 */
private void logoutEvent() {
    log.debug("Logging out");
    try {
        AWSCredentials awsCredentials = s3ServiceMulti.getAWSCredentials();
        String loginName = (awsCredentials.hasFriendlyName() ? awsCredentials.getFriendlyName()
                : awsCredentials.getAccessKey());
        if (loginAwsCredentialsMap.containsKey(loginName)) {
            Component[] components = loginSwitchMenu.getMenuComponents();
            for (int i = 0; i < components.length; i++) {
                JMenuItem menuItem = (JMenuItem) components[i];
                if (loginName.equals(menuItem.getText())) {
                    loginSwitchMenu.remove(components[i]);
                    break;
                }
            }
            loginAwsCredentialsMap.remove(loginName);
            loginSwitchMenu.setEnabled(loginAwsCredentialsMap.size() > 0);
        }

        // Revert to anonymous service.
        s3ServiceMulti = new S3ServiceMulti(new RestS3Service(null, APPLICATION_DESCRIPTION, this), this);
        cloudFrontService = null;

        bucketsTable.clearSelection();
        bucketTableModel.removeAllBuckets();
        objectTableModel.removeAllObjects();

        objectsSummaryLabel.setText(" ");

        ownerFrame.setTitle(APPLICATION_TITLE);
        logoutMenuItem.setEnabled(false);

        refreshBucketMenuItem.setEnabled(false);
        createBucketMenuItem.setEnabled(false);
        bucketLoggingMenuItem.setEnabled(false);

        manageDistributionsMenuItem.setEnabled(false);
    } catch (Exception e) {
        String message = "Unable to log out from S3";
        log.error(message, e);
        ErrorDialog.showDialog(ownerFrame, this, message, e);
    }
}

From source file:org.gcaldaemon.gui.ConfigEditor.java

public final void actionPerformed(ActionEvent evt) {

    // Common actions
    Object source = evt.getSource();
    if (source == null) {
        return;// ww w. j  a  v  a2s . c  o m
    }
    if (source == exitMenu) {
        exit();
        return;
    }
    if (source == saveMenu) {
        save();
        return;
    }
    if (source == logMenu) {
        status(Messages.getString("log.viewer")); //$NON-NLS-1$
        new LogDialog(this, config);
        return;
    }
    if (source == transMenu) {
        status(Messages.getString("translate")); //$NON-NLS-1$
        TranslatorDialog translator = new TranslatorDialog(this);
        String code = translator.getSelectedLanguage();
        if (code != null) {
            setLanguage(code);
        }
        return;
    }
    if (source == aboutMenu) {
        info(Messages.getString("about"), Messages.getString("config.editor") + " - " + Configurator.VERSION); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        return;
    }
    if (source instanceof JMenuItem) {
        JMenuItem item = (JMenuItem) source;
        String param = item.getName();
        if (param != null && param.length() > 1) {
            if (param.charAt(0) == '!') {
                param = param.substring(1);
                int i = param.indexOf('[');
                if (i > 0) {
                    param = param.substring(0, i).trim();
                }
                setLanguage(param);
            } else {
                status(item.getText());
                setLookAndFeel(param.substring(1));
                SwingUtilities.updateComponentTreeUI(this);
            }
        }
    }
}

From source file:org.kepler.gui.component.ToggleLsidAction.java

/**
 * Invoked when an action occurs./*w ww.  j  a v a  2s. c o m*/
 * 
 *@param e
 *            ActionEvent
 */
public void actionPerformed(ActionEvent e) {

    try {

        Object o = e.getSource();
        if (o instanceof JMenuItem) {
            JMenuItem jmi = (JMenuItem) o;
            String lsidStr = jmi.getText();
            if (isDebugging)
                log.debug(getLiid() + " " + lsidStr);
            LibraryManager lm = LibraryManager.getInstance();
            try {
                KeplerLSID newDefaultLSID = new KeplerLSID(lsidStr);
                lm.getIndex().updateDefaultLsid(getLiid(), newDefaultLSID);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(GUIUtil.getParentWindow(jmi), ex.getMessage());
            }
        }

    } catch (Exception exc) {
        exc.printStackTrace();
    }
}

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

/**
 * get Map of name/value pairs containing menu paths of original PTII
 * context- menu items, and their correspondign Action objects
 * //from   w  ww.  jav  a  2s.  co  m
 * @param object
 *            NamedObj
 * @param isWorkflow
 *            boolean - @todo - FIXME - this is a gnarly hack because a
 *            workflow is actually a TypedCompositeActor, so if we just rely
 *            in the "instanceof" checks like we do for other context menus,
 *            this code will assume the workflow is actually an actor, and
 *            will display the actor context menu instead of the workflow
 *            one
 * @return Map
 */
protected Map<String, Action> getOriginalMenuItemsMap(NamedObj object, boolean isWorkflow) {

    Map<String, Action> retMap = new HashMap<String, Action>();
    if (isWorkflow) {
        _menuBaseName = WORKFLOW_BASE_NAME;
    } else if (object instanceof Director) {
        _menuBaseName = DIRECTOR_BASE_NAME;
    } else if (object instanceof Attribute) {
        _menuBaseName = ATTRIB_BASE_NAME;
    } else if (object instanceof ComponentEntity) {
        _menuBaseName = ACTOR_BASE_NAME;
    } else if (object instanceof Port) {
        _menuBaseName = PORT_BASE_NAME;
    } else if (object instanceof Relation) {
        _menuBaseName = LINK_BASE_NAME;
    } else { // catch-all
        _menuBaseName = "UNKNOWN";
        if (isDebugging) {
            log.error("KeplerContextMenuFactory was asked to handle a NamedObj "
                    + "type that was not recognized: " + object.getClassName());
        }
    }
    menuPathPrefixLength = _menuBaseName.length() + MenuMapper.MENU_PATH_DELIMITER.length();

    Iterator i = menuItemFactoryList().iterator();

    int n = 0;
    while (i.hasNext()) {
        MenuItemFactory factory = (MenuItemFactory) i.next();
        JMenuItem menuItem = factory.create(menuItemHolder, object);

        if (menuItem != null) {
            StringBuffer pathBuff = new StringBuffer(_menuBaseName);
            // System.out.println("ptii context menu item found: "+
            // menuItem.getText());
            if (isDebugging) {
                log.debug("Found PTII context-menu item: " + menuItem.getText());
            }
            MenuMapper.storePTIIMenuItems(menuItem, pathBuff, MenuMapper.MENU_PATH_DELIMITER, retMap);
        }
        n++;
    }
    return retMap;
}

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

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

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

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

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

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

            }
        }
    }

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

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

}

From source file:org.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 ww w. ja v a  2 s  .c o 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.openmicroscopy.shoola.env.ui.TaskBarView.java

/**
 * Makes and returns a copy of the specified item.
 *
 * @param original The item to handle.//from   w w w .ja  v a2s . c o  m
 * @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;
}

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

/**
 * Implemented as specified by {@link TaskBar}.
 * @see TaskBar#removeFromMenu(int, JMenuItem)
 *//*from w w w  .  j a  v a  2s .  com*/
public void removeFromMenu(int menuID, JMenuItem entry) {
    if (menuID < 0 || menus.length <= menuID)
        throw new IllegalArgumentException("Invalid menu id: " + menuID + ".");
    Iterator<JMenu> i;
    JMenu menu;
    Component[] comps;
    Component c;
    if (menuID == WINDOW_MENU && entry instanceof JMenu) {
        i = windowMenus.iterator();
        //tmp solution to remove item from the copy of the windows menu.
        while (i.hasNext()) {
            menu = i.next();
            comps = menu.getPopupMenu().getComponents();
            for (int j = 0; j < comps.length; j++) {
                c = comps[j];
                if (c instanceof JMenu) {
                    if (((JMenu) c).getText().equals(entry.getText()))
                        menu.remove(c);
                }
            }
        }
    } else if (menuID == HELP_MENU && entry instanceof JMenu) {
        i = helpMenus.iterator();
        //tmp solution to remove item from the copy of the windows menu.
        while (i.hasNext()) {
            menu = i.next();
            comps = menu.getPopupMenu().getComponents();
            for (int j = 0; j < comps.length; j++) {
                c = comps[j];
                if (c instanceof JMenu) {
                    if (((JMenu) c).getText() == entry.getText()) {
                        menu.remove(c);
                    }
                }
            }
        }
    }
    menus[menuID].remove(entry);
}