Example usage for javax.swing JMenuItem add

List of usage examples for javax.swing JMenuItem add

Introduction

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

Prototype

public Component add(Component comp) 

Source Link

Document

Appends the specified component to the end of this container.

Usage

From source file:edu.ku.brc.af.ui.forms.ResultSetController.java

/**
 * Helper method for creating the menu items.
 * @param menuItem the parent menu it for the menu items
 * @param titleKey the I18N key for the button title
 * @param menuKey the I18N key for the mneumonic 
 * @param cmdType the command/*from w  w w .  j  a  va  2s  .c  o m*/
 */
protected static void createMenuItem(final JMenuItem menuItem, final String titleKey,
        final CommandType cmdType) {
    KeyStroke ks = UIHelper.getKeyStroke(cmdType);
    JMenuItem mi = new JMenuItem(UIRegistry.getInstance().makeAction(commandsHash.get(cmdType),
            getResourceString(titleKey), null, "", ks.getKeyCode(), ks));
    menuItem.add(mi);
}

From source file:maltcms.ui.nb.pipelineRunner.actions.RunMaltcmsPipelinesAction.java

protected static JMenu actionsToMenu(String menuName, Action[] actions, Lookup context) {
    //code from Utilities.actionsToPopup
    // keeps actions for which was menu item created already (do not add them twice)
    Set<Action> counted = new HashSet<>();
    // components to be added (separators are null)
    List<Component> components = new ArrayList<>();

    for (Action action : actions) {
        if (action != null && counted.add(action)) {
            // switch to replacement action if there is some
            if (action instanceof ContextAwareAction) {
                //               System.out.println("Context aware action");
                Action contextAwareAction = ((ContextAwareAction) action).createContextAwareInstance(context);
                if (contextAwareAction == null) {
                    Logger.getLogger(RunMaltcmsPipelinesAction.class.getName()).log(Level.WARNING,
                            "ContextAwareAction.createContextAwareInstance(context) returns null. That is illegal!"
                                    + " action={0}, context={1}",
                            new Object[] { action, context });
                } else {
                    action = contextAwareAction;
                }/*from www  .  j a va 2 s  .  c o  m*/
            }

            JMenuItem item;
            if (action instanceof JMenuItem || action instanceof JMenu) {
                item = (JMenuItem) action;
            } else if (action instanceof Presenter.Popup) {
                //               System.out.println("Popup menu");
                item = ((Presenter.Popup) action).getPopupPresenter();
                if (item == null) {
                    Logger.getLogger(RunMaltcmsPipelinesAction.class.getName()).log(Level.WARNING,
                            "findContextMenuImpl, getPopupPresenter returning null for {0}", action);
                    continue;
                }
            } else if (action instanceof DynamicMenuContent) {
                //               System.out.println("Dynamic content menu");
                DynamicMenuContent dmc = (DynamicMenuContent) action;
                JComponent[] presenters = dmc.getMenuPresenters();
                String name = action.getValue("name").toString();
                item = new JMenuItem(name);
                for (JComponent jc : presenters) {
                    item.add(jc);
                }
            } else {
                //               System.out.println("Plain menu action");
                // We need to correctly handle mnemonics with '&' etc.
                item = ActionPresenterProvider.getDefault().createPopupPresenter(action);
            }

            for (Component c : ActionPresenterProvider.getDefault().convertComponents(item)) {
                if (c instanceof JSeparator) {
                    components.add(null);
                } else {
                    components.add(c);
                }
            }
        } else {
            components.add(null);
        }
    }

    // Now create actual menu. Strip adjacent, leading, and trailing separators.
    JMenu menu = new JMenu(menuName);
    boolean nonempty = false; // has anything been added yet?
    boolean pendingSep = false; // should there be a separator before any following item?
    for (Component c : components) {
        try {
            if (c == null) {
                pendingSep = nonempty;
            } else {
                nonempty = true;
                if (pendingSep) {
                    pendingSep = false;
                    menu.addSeparator();
                }
                menu.add(c);
            }
        } catch (RuntimeException ex) {
            Exceptions.attachMessage(ex, "Current component: " + c); // NOI18N
            Exceptions.attachMessage(ex, "List of components: " + components); // NOI18N
            Exceptions.attachMessage(ex, "List of actions: " + Arrays.asList(actions)); // NOI18N
            Exceptions.printStackTrace(ex);
        }
    }
    return menu;
}

From source file:TreeUtil.java

/** Creates the menus by using recursion */
public JMenuItem getMenus(DefaultMutableTreeNode node, JMenu parentMenu) {
    String name = node.getUserObject().toString();
    int numChild = node.getChildCount();
    if (numChild < 1) {
        JMenuItem tempMenu = new JMenuItem(name);
        tempMenu.setActionCommand(parentMenu.getActionCommand() + "." + name);
        tempMenu.addActionListener(this);
        return tempMenu;
    }/*from  www . j a v  a2  s.  com*/
    JMenu tempMenu = new JMenu(name);
    tempMenu.setActionCommand(parentMenu.getActionCommand() + "." + name);
    tempMenu.addActionListener(this);
    for (int i = 0; i < numChild; i++) {
        tempMenu.add(getMenus((DefaultMutableTreeNode) node.getChildAt(i), tempMenu));
    }
    return tempMenu;
}

From source file:it.cnr.icar.eric.client.ui.swing.RegistryObjectsTable.java

private void createMenuItemsForTaxonomyElements(JMenuItem parentMenuItem, Collection<?> taxonomyElements)
        throws JAXRException {
    Iterator<?> iter = taxonomyElements.iterator();
    while (iter.hasNext()) {
        Object taxonomyElementObj = iter.next();

        Collection<?> children = null;
        if (taxonomyElementObj instanceof ClassificationScheme) {
            children = ((ClassificationScheme) taxonomyElementObj).getChildrenConcepts();
        } else if (taxonomyElementObj instanceof Concept) {
            children = ((Concept) taxonomyElementObj).getChildrenConcepts();
        } else {/*from  ww w.  j a  va 2 s.co  m*/
            throw new JAXRException(CommonResourceBundle.getInstance()
                    .getString("message.unexpectedObjectType", new String[] {
                            taxonomyElementObj.getClass().toString(),
                            "javax.xml.registry.infomodel.ClassificationScheme, javax.xml.registry.infomodel.ClassificationScheme" }));
        }

        String childName = ((RegistryObjectImpl) taxonomyElementObj).getDisplayName();

        JMenuItem childMenuItem = null;

        //Need to handle intermediate nodes different from terminal nodes
        //Intermediate nodes: have a JMenu and JMenuItem children where first child represents themself
        //Leaf nodes: have a JMenuItem that represents themself
        if (children.size() > 0) {
            //Intermediate node
            childMenuItem = new JMenu(childName);

            //Add a first child that represents the intermediate node itself
            JMenuItem firstGrandChildMenuItem = new TaxonomyElementMenuItem(
                    ((RegistryObjectImpl) taxonomyElementObj));
            Action action = new SetStatusAction(((RegistryObjectImpl) taxonomyElementObj));
            firstGrandChildMenuItem.setAction(action);
            childMenuItem.add(firstGrandChildMenuItem);

            //Now add a separator
            JSeparator separator = new JSeparator();
            childMenuItem.add(separator);

            createMenuItemsForTaxonomyElements(childMenuItem, children);
        } else {
            //Leaf node
            childMenuItem = new TaxonomyElementMenuItem(((RegistryObjectImpl) taxonomyElementObj));
            Action action = new SetStatusAction(((RegistryObjectImpl) taxonomyElementObj));
            childMenuItem.setAction(action);
        }
        parentMenuItem.add(childMenuItem);
    }
}

From source file:org.f2o.absurdum.puck.gui.PuckFrame.java

/**
 * Instances and shows Puck's main frame.
 *//*from   w ww .ja  v  a2s  . co  m*/
public PuckFrame() {

    super();

    setLookAndFeel(PuckConfiguration.getInstance().getProperty("look"));

    /*
    LookAndFeelInfo[] lfs = UIManager.getInstalledLookAndFeels();
    for ( int i = 0 ; i < lfs.length ; i++ )
    {
       if ( lfs[i].getName().toLowerCase().contains("nimbus") )
       {
    try 
    {
       UIManager.setLookAndFeel(lfs[i].getClassName());
    } 
    catch (Exception e) //class not found, instantiation exception, etc. (shouldn't happen)
    {
       e.printStackTrace();
    }
            
       }
    }
    */

    setSize(PuckConfiguration.getInstance().getIntegerProperty("windowWidth"),
            PuckConfiguration.getInstance().getIntegerProperty("windowHeight"));
    setLocation(PuckConfiguration.getInstance().getIntegerProperty("windowLocationX"),
            PuckConfiguration.getInstance().getIntegerProperty("windowLocationY"));
    //setSize(600,600);
    if (PuckConfiguration.getInstance().getBooleanProperty("windowMaximized"))
        maximizeIfPossible();
    //setTitle(Messages.getInstance().getMessage("frame.title"));
    refreshTitle();
    left = new JPanel();
    right = new JPanel();
    JScrollPane rightScroll = new JScrollPane(right);
    rightScroll.getVerticalScrollBar().setUnitIncrement(16); //faster scrollbar (by default it was very slow, maybe because component inside is not text component!)
    split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, left, rightScroll) {
        //dynamic resizing of right panel
        /*
        public void setDividerLocation ( int pixels )
        {
              if ( propPanel != null )
              {
          double rightPartSize = getContentPane().getWidth() - pixels - 15;
          System.out.println("rps=" + rightPartSize);
          System.out.println("mnw=" + this.getMinimumSize().getWidth());
          Dimension propPanSize = propPanel.getSize();
          int propPanHeight = 0;
          if (propPanSize != null) propPanHeight = (int) propPanSize.getHeight();
          //propPanel.revalidate();
          System.out.println("h " + propPanHeight);
          //if ( rightPartSize >= propPanel.getMinimumSize().getWidth() )
             propPanel.setPreferredSize(new Dimension((int)rightPartSize,propPanHeight));
             //propPanel.setMinimumSize(new Dimension((int)rightPartSize,propPanHeight));
             //propPanel.setMaximumSize(new Dimension((int)rightPartSize,propPanHeight));
             //propPanel.setSize(new Dimension((int)rightPartSize,propPanHeight));
             propPanel.revalidate();
              }
              super.setDividerLocation(pixels);
        }
        */

    };
    split.setContinuousLayout(true);
    split.setResizeWeight(0.60);
    final int dividerLoc = PuckConfiguration.getInstance().getIntegerProperty("dividerLocation", 0);

    /*
    SwingUtilities.invokeLater(new Runnable(){
    public void run()
    {
    */

    /*   
    }
    });
    */
    split.setOneTouchExpandable(true);
    getContentPane().add(split);

    System.out.println(Toolkit.getDefaultToolkit().getBestCursorSize(20, 20));
    //it's 32x32. Will have to do it.

    //Image img = Toolkit.getDefaultToolkit().createImage( getClass().getResource("addCursor32.png") );

    //Image img = Toolkit.getDefaultToolkit().createImage("addCursor32.png");

    left.setLayout(new BorderLayout());

    //right.setLayout(new BoxLayout(right,BoxLayout.LINE_AXIS));
    if (PuckConfiguration.getInstance().getBooleanProperty("dynamicFormResizing"))
        right.setLayout(new BorderLayout());
    else
        right.setLayout(new FlowLayout());

    propPanel = new PropertiesPanel();
    right.add(propPanel);

    graphPanel = new GraphEditingPanel(propPanel);
    graphPanel.setGrid(Boolean.valueOf(PuckConfiguration.getInstance().getProperty("showGrid")).booleanValue());
    graphPanel.setSnapToGrid(
            Boolean.valueOf(PuckConfiguration.getInstance().getProperty("snapToGrid")).booleanValue());
    propPanel.setGraphEditingPanel(graphPanel);
    tools = new PuckToolBar(graphPanel, propPanel, this);
    left.add(tools, BorderLayout.WEST);
    left.add(graphPanel, BorderLayout.CENTER);

    /*
    Action testAction = 
    new AbstractAction()
    {
       public void actionPerformed ( ActionEvent evt )
       {
          System.out.println("Puck!");
       }
    }
    ;
    testAction.putValue(Action.NAME,"Print Puck");
            
    tools.add(testAction);
    */

    /*
    public void saveChanges ( )
    {
       if ( editingFileName == null )
       {
    //save as... code
       }
       else
       {
    File f = new File(editingFileName);
    try
    {
       Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
       d.appendChild(graphPanel.getWorldNode().getAssociatedPanel().getXML(d));
       Transformer t = TransformerFactory.newInstance().newTransformer();
       Source s = new DOMSource(d);
       Result r = new StreamResult(f);
       t.transform(s,r);
       editingFileName = f.toString();
       refreshTitle();
    }
    catch ( Exception e )
    {
       JOptionPane.showMessageDialog(PuckFrame.this,e,"Whoops!",JOptionPane.ERROR_MESSAGE);
       e.printStackTrace();
    }
       }
    }
    */

    JMenuBar mainMenuBar = new JMenuBar();
    JMenu fileMenu = new JMenu(UIMessages.getInstance().getMessage("menu.file"));
    fileMenu.setMnemonic(KeyEvent.VK_F);
    saveMenuItem = new JMenuItem(UIMessages.getInstance().getMessage("menu.file.save"));
    saveMenuItem.setMnemonic(KeyEvent.VK_S);
    saveMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            if (editingFileName == null)
                JOptionPane.showMessageDialog(PuckFrame.this, "File has no name!", "Whoops!",
                        JOptionPane.ERROR_MESSAGE);
            /*
            File f = new File(editingFileName);
            try
            {
             Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
             d.appendChild(graphPanel.getWorldNode().getAssociatedPanel().getXML(d));
             Transformer t = TransformerFactory.newInstance().newTransformer();
             Source s = new DOMSource(d);
             Result r = new StreamResult(f);
             t.transform(s,r);
             editingFileName = f.toString();
             refreshTitle();
            }
            catch ( Exception e )
            {
             JOptionPane.showMessageDialog(PuckFrame.this,e,"Whoops!",JOptionPane.ERROR_MESSAGE);
             e.printStackTrace();
            }
            */
            try {
                saveChangesInCurrentFile();
            } catch (Exception e) {
                JOptionPane.showMessageDialog(PuckFrame.this, e.getLocalizedMessage(), "Whoops!",
                        JOptionPane.ERROR_MESSAGE);
                e.printStackTrace();
            }
        }
    });
    JMenu newMenu = new JMenu(UIMessages.getInstance().getMessage("menu.file.new"));
    JMenuItem newBlankMenuItem = new JMenuItem(UIMessages.getInstance().getMessage("menu.file.new.blank"));
    //newBlankMenuItem.setMnemonic(KeyEvent.VK_N);
    newBlankMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            GraphElementPanel.emptyQueue(); //stop deferred loads
            graphPanel.clear();
            propPanel.clear();
            JSyntaxBSHCodeFrame.closeAllInstances();
            WorldPanel wp = new WorldPanel(graphPanel);
            WorldNode wn = new WorldNode(wp);
            graphPanel.setWorldNode(wn);
            propPanel.show(graphPanel.getWorldNode());
            resetCurrentlyEditingFile();
            refreshTitle();
            //revalidate(); //only since java 1.7
            //invalidate();
            //validate();
            split.revalidate(); //JComponents do have it before java 1.7 (not JFrame)
        }
    });
    newMenu.add(newBlankMenuItem);
    JMenu templateMenus = new WorldTemplateMenuBuilder(this).getMenu();
    if (templateMenus != null) {
        for (int i = 0; i < templateMenus.getItemCount(); i++) {
            if (i == 0)
                newMenu.add(new JSeparator());
            newMenu.add(templateMenus.getItem(i));
        }
    }
    JMenuItem saveAsMenuItem = new JMenuItem(UIMessages.getInstance().getMessage("menu.file.saveas"));
    saveAsMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            /*
            JFileChooser jfc = new JFileChooser(".");
            int opt = jfc.showSaveDialog(PuckFrame.this);
            if ( opt == JFileChooser.APPROVE_OPTION )
            {
             File f = jfc.getSelectedFile();
             try
             {
                Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
                d.appendChild(graphPanel.getWorldNode().getAssociatedPanel().getXML(d));
                Transformer t = TransformerFactory.newInstance().newTransformer();
                Source s = new DOMSource(d);
                Result r = new StreamResult(f);
                t.transform(s,r);
                editingFileName = f.toString();
                saveMenuItem.setEnabled(true);
                refreshTitle();
             }
             catch ( Exception e )
             {
                JOptionPane.showMessageDialog(PuckFrame.this,e,"Whoops!",JOptionPane.ERROR_MESSAGE);
                e.printStackTrace();
             }
            }
            */
            try {
                saveAs();
                saveMenuItem.setEnabled(true);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(PuckFrame.this, e.getLocalizedMessage(), "Whoops!",
                        JOptionPane.ERROR_MESSAGE);
                e.printStackTrace();
            }
            //saveAs(saveMenuItem);
        }
    });
    JMenuItem openMenuItem = new JMenuItem(UIMessages.getInstance().getMessage("menu.file.open"));
    openMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            //graphPanel.setVisible(false);
            //propPanel.setVisible(false);

            JFileChooser jfc = new JFileChooser(".");
            jfc.setFileFilter(new FiltroFicheroMundo());
            int opt = jfc.showOpenDialog(PuckFrame.this);
            if (opt == JFileChooser.APPROVE_OPTION) {
                File f = jfc.getSelectedFile();
                openFileOrShowError(f);
            }

            //graphPanel.setVisible(true);
            //propPanel.setVisible(true);
        }
    });
    openRecentMenu = new JMenu(UIMessages.getInstance().getMessage("menu.file.recent"));
    JMenuItem exitMenuItem = new JMenuItem(UIMessages.getInstance().getMessage("menu.file.exit"));
    exitMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {

            /*
            int opt = JOptionPane.showConfirmDialog(PuckFrame.this,Messages.getInstance().getMessage("exit.sure.text"),Messages.getInstance().getMessage("exit.sure.title"),JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
                    
            if ( opt == JOptionPane.YES_OPTION )
             System.exit(0);
            */
            userExit();

        }
    });
    JMenu exportMenu = new JMenu(UIMessages.getInstance().getMessage("menu.file.export"));
    JMenuItem exportAppletMenuItem = new JMenuItem(
            UIMessages.getInstance().getMessage("menu.file.export.applet"));
    exportAppletMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            ExportAppletDialog dial = new ExportAppletDialog(PuckFrame.this);
            dial.setVisible(true);
        }
    });
    exportMenu.add(exportAppletMenuItem);

    fileMenu.add(newMenu);
    fileMenu.add(openMenuItem);
    fileMenu.add(openRecentMenu);
    updateRecentMenu();
    fileMenu.add(new JSeparator());
    saveMenuItem.setEnabled(false);
    fileMenu.add(saveMenuItem);
    fileMenu.add(saveAsMenuItem);
    fileMenu.add(exportMenu);
    fileMenu.add(new JSeparator());
    fileMenu.add(exitMenuItem);

    mainMenuBar.add(fileMenu);

    /**
     * Create an Edit menu to support cut/copy/paste.
     */

    JMenu editMenu = new JMenu(UIMessages.getInstance().getMessage("menu.edit"));
    editMenu.setMnemonic(KeyEvent.VK_E);

    JMenuItem findMenuItem = new JMenuItem(UIMessages.getInstance().getMessage("menu.find.entity"));
    findMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            showFindEntityDialog();
        }
    });
    editMenu.add(findMenuItem);
    editMenu.add(new JSeparator());

    JMenuItem aMenuItem = new JMenuItem(new CutAction());
    aMenuItem.setText(UIMessages.getInstance().getMessage("menuaction.cut"));
    aMenuItem.setMnemonic(KeyEvent.VK_T);
    editMenu.add(aMenuItem);

    aMenuItem = new JMenuItem(new CopyAction());
    aMenuItem.setText(UIMessages.getInstance().getMessage("menuaction.copy"));
    aMenuItem.setMnemonic(KeyEvent.VK_C);
    editMenu.add(aMenuItem);

    aMenuItem = new JMenuItem(new PasteAction());
    aMenuItem.setText(UIMessages.getInstance().getMessage("menuaction.paste"));
    aMenuItem.setMnemonic(KeyEvent.VK_P);
    editMenu.add(aMenuItem);

    mainMenuBar.add(editMenu);

    JMenu optionsMenu = new JMenu(UIMessages.getInstance().getMessage("menu.options"));
    JMenu gridMenu = new JMenu(UIMessages.getInstance().getMessage("menu.options.grid"));
    optionsMenu.add(gridMenu);
    final JCheckBoxMenuItem showGridItem = new JCheckBoxMenuItem(
            UIMessages.getInstance().getMessage("menu.options.grid.show"));
    showGridItem.setSelected(
            Boolean.valueOf(PuckConfiguration.getInstance().getProperty("showGrid")).booleanValue());
    gridMenu.add(showGridItem);
    showGridItem.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                graphPanel.setGrid(true);
                PuckConfiguration.getInstance().setProperty("showGrid", "true");
            } else if (e.getStateChange() == ItemEvent.DESELECTED) {
                graphPanel.setGrid(false);
                PuckConfiguration.getInstance().setProperty("showGrid", "false");
            }
            graphPanel.repaint();
        }
    });
    final JCheckBoxMenuItem snapToGridItem = new JCheckBoxMenuItem(
            UIMessages.getInstance().getMessage("menu.options.grid.snap"));
    snapToGridItem.setSelected(
            Boolean.valueOf(PuckConfiguration.getInstance().getProperty("snapToGrid")).booleanValue());
    gridMenu.add(snapToGridItem);
    snapToGridItem.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                graphPanel.setSnapToGrid(true);
                PuckConfiguration.getInstance().setProperty("snapToGrid", "true");
            } else if (e.getStateChange() == ItemEvent.DESELECTED) {
                graphPanel.setSnapToGrid(false);
                PuckConfiguration.getInstance().setProperty("snapToGrid", "false");
            }
            graphPanel.repaint();
        }
    });

    JMenuItem translationModeMenu = new JMenu(UIMessages.getInstance().getMessage("menu.options.translation"));
    ButtonGroup translationGroup = new ButtonGroup();
    final JRadioButtonMenuItem holdMenuItem = new JRadioButtonMenuItem(
            UIMessages.getInstance().getMessage("menu.options.translation.hold"));
    final JRadioButtonMenuItem pushMenuItem = new JRadioButtonMenuItem(
            UIMessages.getInstance().getMessage("menu.options.translation.push"));
    pushMenuItem.setSelected("push".equals(PuckConfiguration.getInstance().getProperty("translateMode")));
    if (!pushMenuItem.isSelected())
        holdMenuItem.setSelected(true);
    translationGroup.add(holdMenuItem);
    translationGroup.add(pushMenuItem);
    holdMenuItem.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent arg0) {
            if (holdMenuItem.isSelected())
                PuckConfiguration.getInstance().setProperty("translateMode", "hold");
            else
                PuckConfiguration.getInstance().setProperty("translateMode", "push");
        }
    });
    translationModeMenu.add(holdMenuItem);
    translationModeMenu.add(pushMenuItem);
    optionsMenu.add(translationModeMenu);

    JMenuItem toolSelectionModeMenu = new JMenu(
            UIMessages.getInstance().getMessage("menu.options.toolselection"));
    ButtonGroup toolSelectionGroup = new ButtonGroup();
    final JRadioButtonMenuItem oneUseMenuItem = new JRadioButtonMenuItem(
            UIMessages.getInstance().getMessage("menu.options.toolselection.oneuse"));
    final JRadioButtonMenuItem multipleUseMenuItem = new JRadioButtonMenuItem(
            UIMessages.getInstance().getMessage("menu.options.toolselection.multipleuse"));
    multipleUseMenuItem.setSelected(
            "multipleUse".equalsIgnoreCase(PuckConfiguration.getInstance().getProperty("toolSelectionMode")));
    if (!multipleUseMenuItem.isSelected())
        oneUseMenuItem.setSelected(true);
    toolSelectionGroup.add(oneUseMenuItem);
    toolSelectionGroup.add(multipleUseMenuItem);
    oneUseMenuItem.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent arg0) {
            if (oneUseMenuItem.isSelected())
                PuckConfiguration.getInstance().setProperty("toolSelectionMode", "oneUse");
            else
                PuckConfiguration.getInstance().setProperty("toolSelectionMode", "multipleUse");
        }
    });
    toolSelectionModeMenu.add(oneUseMenuItem);
    toolSelectionModeMenu.add(multipleUseMenuItem);
    optionsMenu.add(toolSelectionModeMenu);

    JMenuItem sizesMenuItem = new JMenuItem(UIMessages.getInstance().getMessage("menu.options.iconsizes"));
    sizesMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            IconSizesDialog dial = new IconSizesDialog(PuckFrame.this, true);
            dial.setVisible(true);
        }
    });
    optionsMenu.add(sizesMenuItem);

    JMenuItem showHideMenuItem = new JMenuItem(UIMessages.getInstance().getMessage("menu.options.showhide"));
    showHideMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            ShowHideDialog dial = new ShowHideDialog(PuckFrame.this, true);
            dial.setVisible(true);
        }
    });
    optionsMenu.add(showHideMenuItem);

    JMenuItem mapColorsMenuItem = new JMenuItem(UIMessages.getInstance().getMessage("menu.options.mapcolors"));
    mapColorsMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            MapColorsDialog dial = new MapColorsDialog(PuckFrame.this, true);
            dial.setVisible(true);
        }
    });
    optionsMenu.add(mapColorsMenuItem);

    String skinList = PuckConfiguration.getInstance().getProperty("availableSkins");
    if (skinList != null && skinList.trim().length() > 0) {
        JMenu skinsMenu = new JMenu(UIMessages.getInstance().getMessage("menu.skins"));
        StringTokenizer st = new StringTokenizer(skinList, ", ");
        ButtonGroup skinButtons = new ButtonGroup();
        while (st.hasMoreTokens()) {
            final String nextSkin = st.nextToken();
            final JRadioButtonMenuItem skinMenuItem = new JRadioButtonMenuItem(nextSkin);
            skinMenuItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    setSkin(nextSkin);
                    skinMenuItem.setSelected(true);
                }
            });
            if (nextSkin.equals(PuckConfiguration.getInstance().getProperty("skin")))
                skinMenuItem.setSelected(true);
            skinsMenu.add(skinMenuItem);
            skinButtons.add(skinMenuItem);
        }
        optionsMenu.add(skinsMenu);
    }

    JMenu lookFeelMenu = new JMenu(UIMessages.getInstance().getMessage("menu.looks"));
    ButtonGroup lookButtons = new ButtonGroup();
    final JRadioButtonMenuItem defaultLookMenuItem = new JRadioButtonMenuItem(
            UIMessages.getInstance().getMessage("menu.looks.default"));
    if ("default".equals(PuckConfiguration.getInstance().getProperty("look"))) {
        defaultLookMenuItem.setSelected(true);
    }
    lookFeelMenu.add(defaultLookMenuItem);
    lookButtons.add(defaultLookMenuItem);
    defaultLookMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            setLookAndFeel("default");
            defaultLookMenuItem.setSelected(true);
        }
    });
    final JRadioButtonMenuItem systemLookMenuItem = new JRadioButtonMenuItem(
            UIMessages.getInstance().getMessage("menu.looks.system"));
    if ("system".equals(PuckConfiguration.getInstance().getProperty("look"))) {
        systemLookMenuItem.setSelected(true);
    }
    lookFeelMenu.add(systemLookMenuItem);
    lookButtons.add(systemLookMenuItem);
    systemLookMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            setLookAndFeel("system");
            systemLookMenuItem.setSelected(true);
        }
    });
    String additionalLookList = PuckConfiguration.getInstance().getProperty("additionalLooks");
    if (additionalLookList != null && additionalLookList.trim().length() > 0) {
        StringTokenizer st = new StringTokenizer(additionalLookList, ", ");
        while (st.hasMoreTokens()) {
            final String nextLook = st.nextToken();
            final JRadioButtonMenuItem lookMenuItem = new JRadioButtonMenuItem(nextLook);
            lookMenuItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    setLookAndFeel(nextLook);
                    lookMenuItem.setSelected(true);
                }
            });
            if (nextLook.equals(PuckConfiguration.getInstance().getProperty("look"))) {
                lookMenuItem.setSelected(true);
            }
            lookFeelMenu.add(lookMenuItem);
            lookButtons.add(lookMenuItem);
        }
    }
    optionsMenu.add(lookFeelMenu);

    optionsMenu.add(new UILanguageSelectionMenu(this));

    mainMenuBar.add(optionsMenu);

    JMenu toolsMenu = new JMenu(UIMessages.getInstance().getMessage("menu.tools"));

    final JMenuItem verbListMenuItem = new JMenuItem(
            UIMessages.getInstance().getMessage("menu.tools.verblist"));
    verbListMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            WorldPanel wp = (WorldPanel) graphPanel.getWorldNode().getAssociatedPanel();
            VerbListFrame vlf = VerbListFrame.getInstance(wp.getSelectedLanguageCode());
            vlf.setVisible(true);
        }
    });
    toolsMenu.add(verbListMenuItem);

    final JMenuItem validateMenuItem = new JMenuItem(
            UIMessages.getInstance().getMessage("menu.tools.validatebsh"));
    validateMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            BeanShellCodeValidator bscv = new BeanShellCodeValidator(graphPanel);
            if (!bscv.validate()) {
                BeanShellErrorsDialog bsed = new BeanShellErrorsDialog(PuckFrame.this, bscv.getErrorText());
                bsed.setVisible(true);
                //JOptionPane.showMessageDialog(PuckFrame.this, bscv.getErrorText());
            } else {
                JOptionPane.showMessageDialog(PuckFrame.this,
                        UIMessages.getInstance().getMessage("bsh.code.ok"), "OK!",
                        JOptionPane.INFORMATION_MESSAGE);
                //JOptionPane.showMessageDialog(PuckFrame.this, bscv.getErrorText());
            }
        }
    });
    toolsMenu.add(validateMenuItem);

    mainMenuBar.add(toolsMenu);

    JMenu helpMenu = new JMenu(UIMessages.getInstance().getMessage("menu.help"));
    //JHelpAction.startHelpWorker("help/PUCKHelp.hs");
    //JHelpAction helpTocAction = JHelpAction.getShowHelpInstance(Messages.getInstance().getMessage("menu.help.toc"));
    //JHelpAction helpContextSensitiveAction = JHelpAction.getTrackInstance(Messages.getInstance().getMessage("menu.help.context"));
    //final JMenuItem helpTocMenuItem = new JMenuItem(helpTocAction);
    //final JMenuItem helpContextSensitiveMenuItem = new JMenuItem(helpContextSensitiveAction);
    //helpMenu.add(helpTocMenuItem);
    //helpMenu.add(helpContextSensitiveMenuItem);

    final JMenuItem helpMenuItem = new JMenuItem(UIMessages.getInstance().getMessage("menu.help.toc"));
    helpMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            DocumentationLinkDialog dial = new DocumentationLinkDialog(PuckFrame.this, true);
            dial.setVisible(true);
        }
    });
    helpMenu.add(helpMenuItem);

    mainMenuBar.add(helpMenu);

    MenuMnemonicOnTheFly.setMnemonics(mainMenuBar);

    this.setJMenuBar(mainMenuBar);

    //setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            userExit();
        }
    });

    propPanel.show(graphPanel.getWorldNode());

    setVisible(true);

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            if (dividerLoc > 0)
                split.setDividerLocation(dividerLoc);
            else
                split.setDividerLocation(0.60);
        }
    });

}

From source file:org.kuali.test.creator.TestCreator.java

private void createMenuBar() {
    JMenuBar mainMenu = new JMenuBar();

    JMenuItem menu = new JMenu();
    menu.setMnemonic('f');
    menu.setText("File");

    JMenuItem m = new JMenuItem("Reload Configuration");
    m.addActionListener(new ActionListener() {
        @Override/*ww w. j  a  va 2s .  c  o m*/
        public void actionPerformed(ActionEvent evt) {
            handleReloadConfiguation(evt);
        }
    });

    menu.add(m);

    m = new JMenuItem("Schedule Tests...");
    m.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            handleScheduleTests(evt);
        }
    });

    menu.add(m);

    menu.add(new JSeparator());

    saveConfigurationMenuItem = new JMenuItem("Save Repository Configuration");
    saveConfigurationMenuItem.setEnabled(false);

    saveConfigurationMenuItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            testRepositoryTree.saveConfiguration();
            saveConfigurationButton.setEnabled(false);
            saveConfigurationMenuItem.setEnabled(false);
        }
    });

    menu.add(saveConfigurationMenuItem);

    JMenuItem backupRepositoryMenuItem = new JMenuItem("Backup Repository");

    backupRepositoryMenuItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            handleBackupRepository();
        }
    });

    menu.add(backupRepositoryMenuItem);

    menu.add(new JSeparator());

    createTestMenuItem = new JMenuItem("Create Test");

    createTestMenuItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            handleCreateTest(null);
        }
    });

    menu.add(createTestMenuItem);

    menu.add(new JSeparator());

    JMenuItem setup = new JMenu("Setup");

    m = new JMenuItem("Add Platform");
    m.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            handleAddPlatform(evt);
        }
    });
    setup.add(m);

    m = new JMenuItem("Add Database Connection");
    m.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            handleAddDatabaseConnection(evt);
        }
    });
    setup.add(m);

    m = new JMenuItem("Add Web Service");

    m.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            handleAddWebService(evt);
        }
    });

    setup.add(m);

    m = new JMenuItem("Add JMX Connection");

    m.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            handleAddJmxConnection(evt);
        }
    });

    setup.add(m);

    setup.add(new JSeparator());

    m = new JMenuItem("Parameters requiring encryption");
    m.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            handleParametersRequiringEncryptionSetup();
        }
    });

    setup.add(m);

    m = new JMenuItem("Auto replace parameters");
    m.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            handleAutoReplaceParameterSetup();
        }
    });

    setup.add(m);

    setup.add(new JSeparator());

    m = new JMenuItem("Email Setup");
    m.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            handleEmailSetup(evt);
        }
    });

    setup.add(m);

    menu.add(setup);

    menu.add(new JSeparator());

    m = new JMenuItem("Exit");
    m.setMnemonic('x');
    m.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            exitApplication.doClick();
        }
    });

    menu.add(m);

    mainMenu.add(menu);

    menu = new JMenu("Help");
    menu.setMnemonic('h');

    m = new JMenuItem("Contents");
    m.setMnemonic('c');
    menu.add(m);
    m.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            showHelp(evt);
        }
    });

    m = new JMenuItem("About");
    m.setMnemonic('a');
    menu.add(m);

    m.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            showHelpAbout();
        }
    });

    mainMenu.add(menu);

    setJMenuBar(mainMenu);
}

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

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

    // bind
    shotcuts.bindKeyStrokes(menu);

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

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

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

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

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

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

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

    // bind
    shotcuts.bindKeyStrokes(parent);

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

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

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

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

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

From source file:pl.otros.logview.gui.LogViewPanel.java

private JPopupMenu initTableContextMenu() {
    JPopupMenu menu = new JPopupMenu("Menu");
    JMenuItem mark = new JMenuItem("Mark selected rows");
    mark.addActionListener(new MarkRowAction(otrosApplication));
    JMenuItem unmark = new JMenuItem("Unmark selected rows");
    unmark.addActionListener(new UnMarkRowAction(otrosApplication));

    JMenuItem autoResizeMenu = new JMenu("Table auto resize mode");
    autoResizeMenu.setIcon(Icons.TABLE_RESIZE);
    JMenuItem autoResizeSubsequent = new JMenuItem("Subsequent columns");
    autoResizeSubsequent//from ww w  .j a v a2s . c  o  m
            .addActionListener(new TableResizeActionListener(table, JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS));
    JMenuItem autoResizeLast = new JMenuItem("Last column");
    autoResizeLast.addActionListener(new TableResizeActionListener(table, JTable.AUTO_RESIZE_LAST_COLUMN));
    JMenuItem autoResizeNext = new JMenuItem("Next column");
    autoResizeNext.addActionListener(new TableResizeActionListener(table, JTable.AUTO_RESIZE_NEXT_COLUMN));
    JMenuItem autoResizeAll = new JMenuItem("All columns");
    autoResizeAll.addActionListener(new TableResizeActionListener(table, JTable.AUTO_RESIZE_ALL_COLUMNS));
    JMenuItem autoResizeOff = new JMenuItem("Auto resize off");
    autoResizeOff.addActionListener(new TableResizeActionListener(table, JTable.AUTO_RESIZE_OFF));
    autoResizeMenu.add(autoResizeSubsequent);
    autoResizeMenu.add(autoResizeOff);
    autoResizeMenu.add(autoResizeNext);
    autoResizeMenu.add(autoResizeLast);
    autoResizeMenu.add(autoResizeAll);
    JMenu removeMenu = new JMenu("Remove log events");
    removeMenu.setFont(menuLabelFont);
    removeMenu.setIcon(Icons.BIN);
    JLabel removeLabel = new JLabel("Remove by:");
    removeLabel.setFont(menuLabelFont);
    removeMenu.add(removeLabel);

    Map<String, Set<String>> propKeyValue = getPropertiesOfSelectedLogEvents();
    for (AcceptCondition acceptCondition : acceptConditionList) {
        removeMenu.add(new JMenuItem(new RemoveByAcceptanceCriteria(acceptCondition, otrosApplication)));
    }
    for (String propertyKey : propKeyValue.keySet()) {
        for (String propertyValue : propKeyValue.get(propertyKey)) {
            PropertyAcceptCondition propAcceptCondition = new PropertyAcceptCondition(propertyKey,
                    propertyValue);
            removeMenu
                    .add(new JMenuItem(new RemoveByAcceptanceCriteria(propAcceptCondition, otrosApplication)));
        }
    }

    menu.add(new JSeparator());
    JLabel labelMarkingRows = new JLabel("Marking/unmarking rows");
    labelMarkingRows.setFont(menuLabelFont);
    menu.add(labelMarkingRows);
    menu.add(new JSeparator());
    menu.add(mark);
    menu.add(unmark);
    JMenu[] markersMenu = getAutomaticMarkersMenu();
    menu.add(markersMenu[0]);
    menu.add(markersMenu[1]);
    menu.add(new ClearMarkingsAction(otrosApplication));
    menu.add(new JSeparator());
    JLabel labelQuickFilters = new JLabel("Quick filters");
    labelQuickFilters.setFont(menuLabelFont);
    menu.add(labelQuickFilters);
    menu.add(new JSeparator());
    menu.add(focusOnThisThreadAction);
    menu.add(focusOnEventsAfter);
    menu.add(focusOnEventsBefore);
    menu.add(focusOnSelectedClassesAction);
    menu.add(ignoreSelectedEventsClasses);
    menu.add(focusOnSelectedLoggerNameAction);
    menu.add(showCallHierarchyAction);
    for (String propertyKey : propKeyValue.keySet()) {
        for (String propertyValue : propKeyValue.get(propertyKey)) {
            menu.add(new FocusOnSelectedPropertyAction(propertyFilter, propertyFilterPanel.getEnableCheckBox(),
                    otrosApplication, propertyKey, propertyValue));
        }
    }
    menu.add(new JSeparator());
    menu.add(removeMenu);
    menu.add(new JSeparator());
    JLabel labelTableOptions = new JLabel("Table options");
    labelTableOptions.setFont(menuLabelFont);
    menu.add(labelTableOptions);
    menu.add(new JSeparator());
    menu.add(autoResizeMenu);

    menu.add(new JSeparator());
    List<MenuActionProvider> menuActionProviders = otrosApplication.getLogViewPanelMenuActionProvider();
    for (MenuActionProvider menuActionProvider : menuActionProviders) {
        try {
            List<OtrosAction> actions = menuActionProvider.getActions(otrosApplication, this);
            if (actions == null) {
                continue;
            }
            for (OtrosAction action : actions) {
                menu.add(action);
            }
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Cant get action from from provider " + menuActionProvider, e);
        }
    }

    return menu;
}