Example usage for javax.swing JPopupMenu add

List of usage examples for javax.swing JPopupMenu add

Introduction

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

Prototype

public JMenuItem add(Action a) 

Source Link

Document

Appends a new menu item to the end of the menu which dispatches the specified Action object.

Usage

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

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

    initPrefModelListeners();

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

        public void close() {
        }

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

    initSocketConnectionListener();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    preferencesFrame.setSize(750, 520);

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

    pack();

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

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

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

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

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

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

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

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

                            break;
                        }
                    }

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

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

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

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

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

    setVisible(true);

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

    removeSplash();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    final SmallButton stopButton = new SmallButton(stopTutorial);

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

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

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

}

From source file:org.apache.syncope.ide.netbeans.view.ResourceExplorerTopComponent.java

private void rootRightClickAction(final MouseEvent evt) {
    JPopupMenu menu = new JPopupMenu();
    JMenuItem refreshItem = new JMenuItem("Refresh Templates");
    JMenuItem resetConnectionItem = new JMenuItem("Reset Connection");
    menu.add(refreshItem);
    menu.add(resetConnectionItem);//from  w w w .  j  a v a2 s.  co  m

    refreshItem.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(final ActionEvent e) {
            // simulate close and open to refresh the tree
            componentClosed();
            componentOpened();
        }
    });

    resetConnectionItem.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(final ActionEvent evt) {
            ServerDetailsView serverDetails = getRefreshServerDetails();
            // set previous preferences
            Preferences prefs = NbPreferences.forModule(ResourceExplorerTopComponent.class);
            serverDetails.setDetails(prefs.get("scheme", "http"), prefs.get("host", "localhost"),
                    prefs.get("port", "8080"), prefs.get("username", StringUtils.EMPTY),
                    prefs.get("password", StringUtils.EMPTY));
            // reset connection preferences
            prefs.remove("scheme");
            prefs.remove("host");
            prefs.remove("port");
            prefs.remove("username");
            prefs.remove("password");
            serverDetails.setVisible(true);
        }
    });
    menu.show(evt.getComponent(), evt.getX(), evt.getY());
}

From source file:org.apache.syncope.ide.netbeans.view.ResourceExplorerTopComponent.java

private void folderRightClickAction(final MouseEvent evt, final DefaultMutableTreeNode node) {
    JPopupMenu menu = new JPopupMenu();
    JMenuItem addItem = new JMenuItem("New");
    menu.add(addItem);

    addItem.addActionListener(new ActionListener() {

        @Override/*from w w w .j  a  v  a  2 s  . c om*/
        public void actionPerformed(final ActionEvent e) {
            String name = JOptionPane.showInputDialog("Enter Name");
            boolean added = false;
            if (!"exit".equals(e.getActionCommand())) {

                if (node.getUserObject().equals(PluginConstants.MAIL_TEMPLATES)) {
                    MailTemplateTO mailTemplate = new MailTemplateTO();
                    mailTemplate.setKey(name);
                    added = mailTemplateManagerService.create(mailTemplate);
                    mailTemplateManagerService.setFormat(name, MailTemplateFormat.HTML,
                            IOUtils.toInputStream("//Enter Content here", encodingPattern));
                    mailTemplateManagerService.setFormat(name, MailTemplateFormat.TEXT,
                            IOUtils.toInputStream("//Enter Content here", encodingPattern));
                    try {
                        openMailEditor(name);
                    } catch (IOException ex) {
                        Exceptions.printStackTrace(ex);
                    }
                } else {
                    ReportTemplateTO reportTemplate = new ReportTemplateTO();
                    reportTemplate.setKey(name);
                    added = reportTemplateManagerService.create(reportTemplate);
                    reportTemplateManagerService.setFormat(name, ReportTemplateFormat.FO,
                            IOUtils.toInputStream("//Enter content here", encodingPattern));
                    reportTemplateManagerService.setFormat(name, ReportTemplateFormat.CSV,
                            IOUtils.toInputStream("//Enter content here", encodingPattern));
                    reportTemplateManagerService.setFormat(name, ReportTemplateFormat.HTML,
                            IOUtils.toInputStream("//Enter content here", encodingPattern));
                    try {
                        openReportEditor(name);
                    } catch (IOException ex) {
                        Exceptions.printStackTrace(ex);
                    }
                }

                if (added) {
                    node.add(new DefaultMutableTreeNode(name));
                    treeModel.reload(node);
                } else {
                    JOptionPane.showMessageDialog(null, "Error while creating new element", "Error",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    });

    menu.show(evt.getComponent(), evt.getX(), evt.getY());
}

From source file:org.apache.syncope.ide.netbeans.view.ResourceExplorerTopComponent.java

private void leafRightClickAction(final MouseEvent evt, final DefaultMutableTreeNode node) {
    JPopupMenu menu = new JPopupMenu();
    JMenuItem deleteItem = new JMenuItem("Delete");
    menu.add(deleteItem);

    deleteItem.addActionListener(new ActionListener() {

        @Override//from  ww w . j  a  v a  2  s  .co  m
        public void actionPerformed(final ActionEvent e) {
            int result = JOptionPane.showConfirmDialog(null, "Are you sure to delete the item?");
            if (result == JOptionPane.OK_OPTION) {
                DefaultMutableTreeNode parent = (DefaultMutableTreeNode) node.getParent();
                boolean deleted;
                if (parent.getUserObject().equals(PluginConstants.MAIL_TEMPLATES)) {
                    deleted = mailTemplateManagerService.delete((String) node.getUserObject());
                } else {
                    deleted = reportTemplateManagerService.delete((String) node.getUserObject());
                }
                if (deleted) {
                    node.removeFromParent();
                    treeModel.reload(parent);
                } else {
                    JOptionPane.showMessageDialog(null, "Error while deleting new element", "Error",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    });

    menu.show(evt.getComponent(), evt.getX(), evt.getY());
}

From source file:org.broad.igv.track.TrackMenuUtils.java

public static void addStandardItems(JPopupMenu menu, Collection<Track> tracks, TrackClickEvent te) {

    boolean hasDataTracks = false;
    boolean hasFeatureTracks = false;
    boolean hasOtherTracks = false;
    for (Track track : tracks) {

        //  TODO -- this is ugly, refactor to remove instanceof
        if (track instanceof DataTrack) {
            hasDataTracks = true;// w w w  .ja  v a  2s  . c om
        } else if (track instanceof FeatureTrack) {
            hasFeatureTracks = true;
        } else {
            hasOtherTracks = true;
        }
        if (hasDataTracks && hasFeatureTracks && hasOtherTracks) {
            break;
        }
    }

    boolean featureTracksOnly = hasFeatureTracks && !hasDataTracks && !hasOtherTracks;
    boolean dataTracksOnly = !hasFeatureTracks && hasDataTracks && !hasOtherTracks;

    addSharedItems(menu, tracks, hasFeatureTracks);
    menu.addSeparator();
    if (dataTracksOnly) {
        addDataItems(menu, tracks);
    } else if (featureTracksOnly) {
        addFeatureItems(menu, tracks, te);
    }

    menu.addSeparator();
    menu.add(getRemoveMenuItem(tracks));

}

From source file:org.broad.igv.track.TrackMenuUtils.java

public static void addZoomItems(JPopupMenu menu, final ReferenceFrame frame) {

    if (FrameManager.isGeneListMode()) {
        JMenuItem item = new JMenuItem("Reset panel to '" + frame.getName() + "'");
        item.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                frame.reset();// www  .j ava  2 s  . com
                // TODO -- paint only panels for this frame
            }
        });
        menu.add(item);
    }

    JMenuItem zoomOutItem = new JMenuItem("Zoom out");
    zoomOutItem.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent evt) {
            frame.incrementZoom(-1);
        }
    });
    menu.add(zoomOutItem);

    JMenuItem zoomInItem = new JMenuItem("Zoom in");
    zoomInItem.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent evt) {
            frame.incrementZoom(1);
        }
    });
    menu.add(zoomInItem);

}

From source file:org.broad.igv.track.TrackMenuUtils.java

/**
 * Return popup menu with items applicable to data tracks
 *
 * @return/*w w  w  .  ja va2 s .  c om*/
 */
public static void addDataItems(JPopupMenu menu, final Collection<Track> tracks) {

    if (log.isDebugEnabled()) {
        log.debug("enter getDataPopupMenu");
    }

    final String[] labels = { "Heatmap", "Bar Chart", "Scatterplot", "Line Plot" };
    final Class[] renderers = { HeatmapRenderer.class, BarChartRenderer.class, PointsRenderer.class,
            LineplotRenderer.class };

    //JLabel popupTitle = new JLabel(LEADING_HEADING_SPACER + title, JLabel.CENTER);

    JLabel rendererHeading = new JLabel(LEADING_HEADING_SPACER + "Type of Graph", JLabel.LEFT);
    rendererHeading.setFont(UIConstants.boldFont);

    menu.add(rendererHeading);

    // Get existing selections
    Set<Class> currentRenderers = new HashSet<Class>();
    for (Track track : tracks) {
        if (track.getRenderer() != null) {
            currentRenderers.add(track.getRenderer().getClass());
        }
    }

    // Create and renderer menu items
    for (int i = 0; i < labels.length; i++) {
        JCheckBoxMenuItem item = new JCheckBoxMenuItem(labels[i]);
        final Class rendererClass = renderers[i];
        if (currentRenderers.contains(rendererClass)) {
            item.setSelected(true);
        }
        item.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                changeRenderer(tracks, rendererClass);
            }
        });
        menu.add(item);
    }
    menu.addSeparator();

    // Get union of all valid window functions for selected tracks
    Set<WindowFunction> avaibleWindowFunctions = new HashSet();
    for (Track track : tracks) {
        avaibleWindowFunctions.addAll(track.getAvailableWindowFunctions());
    }
    avaibleWindowFunctions.add(WindowFunction.none);

    // dataPopupMenu.addSeparator();
    // Collection all window functions for selected tracks
    Set<WindowFunction> currentWindowFunctions = new HashSet<WindowFunction>();
    for (Track track : tracks) {
        if (track.getWindowFunction() != null) {
            currentWindowFunctions.add(track.getWindowFunction());
        }
    }

    if (avaibleWindowFunctions.size() > 1 || currentWindowFunctions.size() > 1) {
        JLabel statisticsHeading = new JLabel(LEADING_HEADING_SPACER + "Windowing Function", JLabel.LEFT);
        statisticsHeading.setFont(UIConstants.boldFont);

        menu.add(statisticsHeading);

        for (final WindowFunction wf : ORDERED_WINDOW_FUNCTIONS) {
            JCheckBoxMenuItem item = new JCheckBoxMenuItem(wf.getDisplayName());
            if (avaibleWindowFunctions.contains(wf) || currentWindowFunctions.contains(wf)) {
                if (currentWindowFunctions.contains(wf)) {
                    item.setSelected(true);
                }
                item.addActionListener(new ActionListener() {

                    public void actionPerformed(ActionEvent evt) {
                        changeStatType(wf.toString(), tracks);
                    }
                });
                menu.add(item);
            }
        }
        menu.addSeparator();
    }

    menu.add(getDataRangeItem(tracks));
    menu.add(getHeatmapScaleItem(tracks));

    if (tracks.size() > 0) {
        menu.add(getLogScaleItem(tracks));
    }

    menu.add(getAutoscaleItem(tracks));

    menu.add(getShowDataRangeItem(tracks));

    menu.addSeparator();
    menu.add(getChangeKMPlotItem(tracks));

}

From source file:org.broad.igv.track.TrackMenuUtils.java

/**
 * Return popup menu with items applicable to feature tracks
 *
 * @return//from  w  ww . j  a  v a2 s  . c om
 */
private static void addFeatureItems(JPopupMenu featurePopupMenu, final Collection<Track> tracks,
        TrackClickEvent te) {

    addDisplayModeItems(tracks, featurePopupMenu);

    if (tracks.size() == 1) {
        Track t = tracks.iterator().next();
        Feature f = t.getFeatureAtMousePosition(te);
        if (f != null) {
            featurePopupMenu.addSeparator();

            // If we are over an exon, copy its sequence instead of the entire feature.
            if (f instanceof IGVFeature) {
                double position = te.getChromosomePosition();
                Collection<Exon> exons = ((IGVFeature) f).getExons();
                if (exons != null) {
                    for (Exon exon : exons) {
                        if (position > exon.getStart() && position < exon.getEnd()) {
                            f = exon;
                            break;
                        }
                    }
                }
            }

            featurePopupMenu.add(getCopyDetailsItem(f, te));
            featurePopupMenu.add(getCopySequenceItem(f));
        }
    }

    featurePopupMenu.addSeparator();
    featurePopupMenu.add(getChangeFeatureWindow(tracks));

    //---------------------//
    //Track analysis
    if (Globals.toolsMenuEnabled && tracks.size() >= 2) {

        JMenuItem item = new JMenuItem("Create Overlap Track");
        item.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String newName = JOptionPane.showInputDialog(IGV.getMainFrame(), "Enter overlap track name: ",
                        "Overlaps");

                if (newName == null || newName.trim() == "") {
                    return;
                }
                CombinedFeatureSource source = new CombinedFeatureSource(tracks,
                        CombinedFeatureSource.Operation.MULTIINTER);
                Track newTrack = new FeatureTrack("", newName, source);

                IGV.getInstance().getTrackPanel(IGV.FEATURE_PANEL_NAME).addTrack(newTrack);
                IGV.getInstance().repaint();
            }
        });
        item.setEnabled(CombinedFeatureSource.checkBEDToolsPathValid());
        featurePopupMenu.add(item);
    }

    //--------------------//
}

From source file:org.broad.igv.track.TrackMenuUtils.java

/**
 * Popup menu with items applicable to both feature and data tracks
 *
 * @return// w  w w.  j  av a2s . c o  m
 */
public static void addSharedItems(JPopupMenu menu, final Collection<Track> tracks, boolean hasFeatureTracks) {

    //JLabel trackSettingsHeading = new JLabel(LEADING_HEADING_SPACER + "Track Settings", JLabel.LEFT);
    //trackSettingsHeading.setFont(boldFont);
    //menu.add(trackSettingsHeading);

    menu.add(getTrackRenameItem(tracks));

    String colorLabel = hasFeatureTracks ? "Change Track Color..." : "Change Track Color (Positive Values)...";
    JMenuItem item = new JMenuItem(colorLabel);
    item.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            changeTrackColor(tracks);
        }
    });
    menu.add(item);

    if (!hasFeatureTracks) {

        // Change track color by attribute
        item = new JMenuItem("Change Track Color (Negative Values)...");
        item.setToolTipText(
                "Change the alternate track color.  This color is used when graphing negative values");
        item.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                changeAltTrackColor(tracks);
            }
        });
        menu.add(item);
    }

    menu.add(getChangeTrackHeightItem(tracks));
    menu.add(getChangeFontSizeItem(tracks));
}

From source file:org.broad.igv.track.TrackMenuUtils.java

public static void addDisplayModeItems(final Collection<Track> tracks, JPopupMenu menu) {

    // Find "most representative" state from track collection
    Map<Track.DisplayMode, Integer> counts = new HashMap<Track.DisplayMode, Integer>(
            Track.DisplayMode.values().length);
    Track.DisplayMode currentMode = null;

    for (Track t : tracks) {
        Track.DisplayMode mode = t.getDisplayMode();
        if (counts.containsKey(mode)) {
            counts.put(mode, counts.get(mode) + 1);
        } else {// w ww  . j  a v a 2 s  .c o m
            counts.put(mode, 1);
        }
    }

    int maxCount = -1;
    for (Map.Entry<Track.DisplayMode, Integer> count : counts.entrySet()) {
        if (count.getValue() > maxCount) {
            currentMode = count.getKey();
            maxCount = count.getValue();
        }
    }

    ButtonGroup group = new ButtonGroup();
    Map<String, Track.DisplayMode> modes = new LinkedHashMap<String, Track.DisplayMode>(4);
    modes.put("Collapsed", Track.DisplayMode.COLLAPSED);
    modes.put("Expanded", Track.DisplayMode.EXPANDED);
    modes.put("Squished", Track.DisplayMode.SQUISHED);
    boolean showAS = Boolean.parseBoolean(System.getProperty("showAS", "false"));
    if (showAS) {
        modes.put("Alternative Splice", Track.DisplayMode.ALTERNATIVE_SPLICE);
    }
    for (final Map.Entry<String, Track.DisplayMode> entry : modes.entrySet()) {
        JRadioButtonMenuItem mm = new JRadioButtonMenuItem(entry.getKey());
        mm.setSelected(currentMode == entry.getValue());
        mm.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                setTrackDisplayMode(tracks, entry.getValue());
                refresh();
            }
        });
        group.add(mm);
        menu.add(mm);
    }

}