List of usage examples for javax.swing JPopupMenu show
public void show(Component invoker, int x, int y)
From source file:com.haulmont.cuba.desktop.sys.DesktopWindowManager.java
public void showTabPopup(MouseEvent e) { JComponent tabHeaderComponent = (JComponent) e.getComponent(); int tabIndex = getTabIndex(tabHeaderComponent); JComponent tabContent = (JComponent) tabsPane.getComponentAt(tabIndex); WindowBreadCrumbs windowBreadCrumbs = tabs.get(tabContent); Window window = windowBreadCrumbs.getCurrentWindow(); JPopupMenu popupMenu = createWindowPopupMenu(window); if (popupMenu.getComponentCount() > 0) { popupMenu.show(tabHeaderComponent, e.getX(), e.getY()); }//w w w . j av a2 s. co m }
From source file:net.sf.jabref.gui.openoffice.OpenOfficePanel.java
private void showSettingsPopup() { JPopupMenu menu = new JPopupMenu(); final JCheckBoxMenuItem autoSync = new JCheckBoxMenuItem( Localization.lang("Automatically sync bibliography when inserting citations"), preferences.syncWhenCiting()); final JRadioButtonMenuItem useActiveBase = new JRadioButtonMenuItem( Localization.lang("Look up BibTeX entries in the active tab only")); final JRadioButtonMenuItem useAllBases = new JRadioButtonMenuItem( Localization.lang("Look up BibTeX entries in all open databases")); final JMenuItem clearConnectionSettings = new JMenuItem(Localization.lang("Clear connection settings")); ButtonGroup bg = new ButtonGroup(); bg.add(useActiveBase);/*from www .ja va 2 s.co m*/ bg.add(useAllBases); if (preferences.useAllDatabases()) { useAllBases.setSelected(true); } else { useActiveBase.setSelected(true); } autoSync.addActionListener(e -> preferences.setSyncWhenCiting(autoSync.isSelected())); useAllBases.addActionListener(e -> preferences.setUseAllDatabases(useAllBases.isSelected())); useActiveBase.addActionListener(e -> preferences.setUseAllDatabases(!useActiveBase.isSelected())); clearConnectionSettings.addActionListener(e -> frame.output(preferences.clearConnectionSettings())); menu.add(autoSync); menu.addSeparator(); menu.add(useActiveBase); menu.add(useAllBases); menu.addSeparator(); menu.add(clearConnectionSettings); menu.show(settingsB, 0, settingsB.getHeight()); }
From source file:ca.phon.ipamap.IpaMap.java
private void init() { setLayout(new BorderLayout()); // favorites//from w w w. j a va 2s. c o m IpaGrids favData = getFavData(); final Grid fg = favData.getGrid().get(0); favPanel = getGridPanel(fg); favPanel.setCollapsed(getSavedSectionToggle(fg.getName())); favToggleButton = getToggleButton(fg, favPanel); favToggleButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setSavedSectionToggle(fg.getName(), !getSavedSectionToggle(fg.getName())); } }); JPanel favSection = new JPanel(new VerticalLayout(0)); favSection.add(favToggleButton); favSection.add(favPanel); favContainer = favSection; // search Grid emptyGrid = (new ObjectFactory()).createGrid(); emptyGrid.setName("Search Results (0)"); emptyGrid.setRows(0); emptyGrid.setCols(0); searchPanel = getGridPanel(emptyGrid); searchToggleButton = getToggleButton(emptyGrid, searchPanel); final JButton searchButton = new JButton("Search"); searchButton.putClientProperty("JComponent.sizeVariant", "small"); searchButton.addActionListener(this::showSearchFrame); JPanel searchSection = new JPanel(new VerticalLayout(0)); searchSection.add(searchButton); searchSection.add(searchToggleButton); searchContainer = searchSection; // static content final JPanel centerPanel = new JPanel(new VerticalLayout(0)); IpaGrids grids = getGridData(); for (final Grid grid : grids.getGrid()) { final JXCollapsiblePane cp = getGridPanel(grid); cp.setCollapsed(getSavedSectionToggle(grid.getName())); JXButton toggleBtn = getToggleButton(grid, cp); toggleBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setSavedSectionToggle(grid.getName(), !getSavedSectionToggle(grid.getName())); } }); toggleButtons.add(toggleBtn); centerPanel.add(toggleBtn); centerPanel.add(cp); gridPanels.add(cp); } scrollPane = new JScrollPane(centerPanel); scrollPane.setAutoscrolls(true); scrollPane.setWheelScrollingEnabled(true); // scrollPane.setViewportView(centerPanel); add(scrollPane, BorderLayout.CENTER); // JPanel btmPanel = new JPanel(new BorderLayout()); // scalePanel.add(smallLbl, BorderLayout.WEST); // scalePanel.add(scaleSlider, BorderLayout.CENTER); // scalePanel.add(largeLbl, BorderLayout.EAST); final JButton scrollBtn = new JButton("-"); scrollBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // popupMenu.show(scrollBtn, 0, scrollBtn.getHeight()); JPopupMenu ctxMenu = new JPopupMenu(); setupContextMenu(ctxMenu, scrollBtn); ctxMenu.show(scrollBtn, 0, scrollBtn.getHeight()); } }); // Font infoFont = new Font("Courier New", Font.PLAIN, 12); infoLabel = new JLabel(); infoLabel.setFont(infoLabel.getFont().deriveFont(Font.ITALIC)); infoLabel.setText("[]"); infoLabel.setOpaque(false); statusBar = new JXStatusBar(); statusBar.setLayout(new BorderLayout()); statusBar.add(infoLabel, BorderLayout.CENTER); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); scrollPane.setCorner(ScrollPaneConstants.LOWER_RIGHT_CORNER, scrollBtn); add(statusBar, BorderLayout.SOUTH); JPanel topPanel = new JPanel(new VerticalLayout(0)); topPanel.add(searchSection); topPanel.add(favSection); add(topPanel, BorderLayout.NORTH); }
From source file:forge.screens.match.CMatchUI.java
@Override public SpellAbility getAbilityToPlay(List<SpellAbility> abilities, ITriggerEvent triggerEvent) { if (triggerEvent == null) { if (abilities.isEmpty()) { return null; }/*from w w w. j a va 2 s. co m*/ if (abilities.size() == 1) { return abilities.get(0); } return GuiChoose.oneOrNone("Choose ability to play", abilities); } if (abilities.isEmpty()) { return null; } if (abilities.size() == 1 && !abilities.get(0).promptIfOnlyPossibleAbility()) { if (abilities.get(0).canPlay()) { return abilities.get(0); //only return ability if it's playable, otherwise return null } return null; } //show menu if mouse was trigger for ability final JPopupMenu menu = new JPopupMenu("Abilities"); boolean enabled; boolean hasEnabled = false; int shortcut = KeyEvent.VK_1; //use number keys as shortcuts for abilities 1-9 for (final SpellAbility ab : abilities) { enabled = ab.canPlay(); if (enabled) { hasEnabled = true; } GuiUtils.addMenuItem(menu, FSkin.encodeSymbols(ab.toString(), true), shortcut > 0 ? KeyStroke.getKeyStroke(shortcut, 0) : null, new Runnable() { @Override public void run() { CPrompt.SINGLETON_INSTANCE.selectAbility(ab); } }, enabled); if (shortcut > 0) { shortcut++; if (shortcut > KeyEvent.VK_9) { shortcut = 0; //stop adding shortcuts after 9 } } } if (hasEnabled) { //only show menu if at least one ability can be played SwingUtilities.invokeLater(new Runnable() { //use invoke later to ensure first ability selected by default public void run() { MenuSelectionManager.defaultManager() .setSelectedPath(new MenuElement[] { menu, menu.getSubElements()[0] }); } }); MouseEvent mouseEvent = ((MouseTriggerEvent) triggerEvent).getMouseEvent(); menu.show(mouseEvent.getComponent(), mouseEvent.getX(), mouseEvent.getY()); } return null; //delay ability until choice made }
From source file:com.github.dougkelly88.FLIMPlateReaderGUI.FLIMClasses.GUIComponents.FLIMPanel.java
private void setControlDefaults() { String[] colName = { "Delays (ps)" }; int max = 16666; try {/*w w w . j a v a 2s. c om*/ max = Integer.parseInt(core_.getProperty("Laser", "Frequency")); } catch (Exception e) { } tableModel_ = new DelayTableModel(colName, (sap_.getDelaysArray()).get(0), 0, max, 25); tableModel_.addTableModelListener(new TableModelListener() { @Override public void tableChanged(TableModelEvent e) { sap_.setDelaysArray(0, tableModel_.getData()); fm_.setGatingData((sap_.getDelaysArray()).get(0)); var_.delays = tableModel_.getData(); } }); delayTable_ = new JTable() { @Override public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { Component comp = super.prepareRenderer(renderer, row, column); int modelRow = convertRowIndexToModel(row); int modelColumn = convertColumnIndexToModel(column); if (modelColumn != 0 && modelRow != 0) { comp.setBackground(Color.GREEN); } return comp; } }; delayTable_.setModel(tableModel_); delayTable_.setSurrendersFocusOnKeystroke(true); delayTable_.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE); JScrollPane scroller = new javax.swing.JScrollPane(delayTable_); delayTable_.setPreferredScrollableViewportSize(new java.awt.Dimension(60, 100)); delayTablePanel.setLayout(new BorderLayout()); delayTablePanel.add(scroller, BorderLayout.CENTER); final JPopupMenu popupMenu = new JPopupMenu(); JMenuItem deleteItem = new JMenuItem("Delete delay"); deleteItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int r = delayTable_.getSelectedRow(); tableModel_.removeRow(r); } }); JMenuItem addItem = new JMenuItem("Add delay"); addItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int r = delayTable_.getSelectedRow(); tableModel_.insertRow(r + 1, 0); } }); popupMenu.add(addItem); popupMenu.add(deleteItem); delayTable_.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { // System.out.println("pressed"); } public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { JTable source = (JTable) e.getSource(); int row = source.rowAtPoint(e.getPoint()); int column = source.columnAtPoint(e.getPoint()); if (!source.isRowSelected(row)) source.changeSelection(row, column, false, false); popupMenu.show(e.getComponent(), e.getX(), e.getY()); } } }); // Set up slider controls mcpSlider_ = new SliderControl("MCP voltage (V)", 300, 850, 750); mcpVoltagePanel.setLayout(new BorderLayout()); mcpVoltagePanel.add(mcpSlider_, BorderLayout.SOUTH); mcpSlider_.addPropertyChangeListener(new java.beans.PropertyChangeListener() { @Override public void propertyChange(java.beans.PropertyChangeEvent evt) { mcpSliderPropertyChange(evt); } }); gatewidthSlider_ = new SliderControl("Gate width (ps)", 200, 7000, 3000); gatewidthPanel.setLayout(new BorderLayout()); gatewidthPanel.add(gatewidthSlider_, BorderLayout.SOUTH); gatewidthSlider_.addPropertyChangeListener(new java.beans.PropertyChangeListener() { @Override public void propertyChange(java.beans.PropertyChangeEvent evt) { gatewidthSliderPropertyChange(evt); } }); HRIControlsPanel.revalidate(); HRIControlsPanel.repaint(); slowDelaySlider_ = new SliderControl("Current delay setting (ps)", 0, 20000, 0); slowCurrentDelayPanel.setLayout(new BorderLayout()); slowCurrentDelayPanel.add(slowDelaySlider_, BorderLayout.SOUTH); slowDelaySlider_.addPropertyChangeListener(new java.beans.PropertyChangeListener() { @Override public void propertyChange(java.beans.PropertyChangeEvent evt) { slowDelaySlider_.setValue(tableModel_.validateData(slowDelaySlider_.getValue().intValue())); slowDelaySliderPropertyChange(evt); } }); fastDelaySlider_ = new SliderControl("Current delay setting (ps)", 0, 20000, 0); fastCurrentDelayPanel.setLayout(new BorderLayout()); fastCurrentDelayPanel.add(fastDelaySlider_, BorderLayout.SOUTH); fastDelaySlider_.addPropertyChangeListener(new java.beans.PropertyChangeListener() { @Override public void propertyChange(java.beans.PropertyChangeEvent evt) { fastDelaySlider_.setValue(tableModel_.validateData(fastDelaySlider_.getValue().intValue())); fastDelaySliderPropertyChange(evt); } }); delayBoxTabbedPane.revalidate(); delayBoxTabbedPane.repaint(); fm_ = new FindMaxpoint(); maxpointGraphPanel.setLayout(new BorderLayout()); chartPanel_ = new ChartPanel(fm_.getChart()); maxpointGraphPanel.add(chartPanel_, BorderLayout.NORTH); // for some reason maxpointGraphPanel's height and width are returned 0 // so hardcode for now... chartPanel_.setMaximumDrawWidth(500); chartPanel_.setMaximumDrawHeight(200); chartPanel_.setPreferredSize(new Dimension(500, 200)); // Set values for other controls based on underlying data to ensure // that all controls are in a consistent state. scanDelCheck.setSelected(sap_.getUseScanFLIM()); }
From source file:corelyzer.ui.CorelyzerApp.java
public void mousePressed(final MouseEvent e) { // From JDK Doc // Note: Popup menus are triggered differently on different systems. // Therefore, isPopupTrigger should be checked in both mousePressed and // mouseReleased for proper cross-platform functionality. Point p = e.getPoint();//from ww w . j a v a 2 s .co m Object actionSource = e.getSource(); if (actionSource instanceof JList) { // find the index of the clicked item in the JList int index = ((JList) e.getSource()).locationToIndex(e.getPoint()); if (index < 0) { return; } // show our popup menu if it was a right/ctrl-click if (e.isPopupTrigger()) { if (actionSource.equals(sessionList)) { Session s = (Session) sessionList.getSelectedValue(); JMenuItem t; // Show label switching if (s == null) { return; } String l = s.isShow() ? "Hide" : "Show"; t = (JMenuItem) sessionPopupMenu.getComponent(0); t.setText(l); sessionPopupMenu.show(e.getComponent(), p.x, p.y); } else if (actionSource.equals(trackList)) { ((JList) e.getSource()).setSelectedIndex(index); // Update context-aware show/hide TrackSceneNode t = (TrackSceneNode) trackList.getSelectedValue(); if ((t != null) && (t.getId() >= 0)) { boolean isShown = SceneGraph.getTrackShow(t.getId()); String label = isShown ? "Hide" : "Show"; ((JMenuItem) trackPopupMenu.getComponent(0)).setText(label); } trackPopupMenu.show(e.getComponent(), p.x, p.y); } else if (actionSource.equals(sectionList)) { int[] rows = getSectionList().getSelectedIndices(); JPopupMenu menu = sectionListPopupMenu(rows); menu.show(e.getComponent(), p.x, p.y); } else if (actionSource.equals(dataFileList)) { ((JList) e.getSource()).setSelectedIndex(index); dataPopupMenu.show(e.getComponent(), p.x, p.y); } } } }
From source file:corelyzer.ui.CorelyzerApp.java
public void mouseReleased(final MouseEvent e) { // From JDK Doc // Note: Popup menus are triggered differently on different systems. // Therefore, isPopupTrigger should be checked in both mousePressed and // mouseReleased for proper cross-platform functionality. Point p = e.getPoint();// w ww .ja va 2 s . co m Object actionSource = e.getSource(); if (actionSource instanceof JList) { // find the index of the clicked item in the JList int index = ((JList) e.getSource()).locationToIndex(e.getPoint()); if (index < 0) { return; } // show our popup menu if it was a right/ctrl-click if (e.isPopupTrigger()) { if (actionSource.equals(sessionList)) { Session s = (Session) sessionList.getSelectedValue(); JMenuItem t; // Show label switching if (s == null) { return; } String l = s.isShow() ? "Hide" : "Show"; t = (JMenuItem) sessionPopupMenu.getComponent(0); t.setText(l); sessionPopupMenu.show(e.getComponent(), p.x, p.y); } else if (actionSource.equals(trackList)) { ((JList) e.getSource()).setSelectedIndex(index); // Update context-aware show/hide TrackSceneNode t = (TrackSceneNode) trackList.getSelectedValue(); if ((t != null) && (t.getId() >= 0)) { boolean isShown = SceneGraph.getTrackShow(t.getId()); String label = isShown ? "Hide" : "Show"; ((JMenuItem) trackPopupMenu.getComponent(0)).setText(label); } trackPopupMenu.show(e.getComponent(), p.x, p.y); } else if (actionSource.equals(sectionList)) { int[] rows = getSectionList().getSelectedIndices(); JPopupMenu menu = sectionListPopupMenu(rows); menu.show(e.getComponent(), p.x, p.y); } else if (actionSource.equals(dataFileList)) { ((JList) e.getSource()).setSelectedIndex(index); dataPopupMenu.show(e.getComponent(), p.x, p.y); } } } }
From source file:com.intuit.tank.tools.debugger.AgentDebuggerFrame.java
/** * @throws HeadlessException/*from w w w. ja v a 2 s . co m*/ */ public AgentDebuggerFrame(final boolean isStandalone, String serviceUrl) throws HeadlessException { super("Intuit Tank Agent Debugger"); workingDir = PanelBuilder.createWorkingDir(this, serviceUrl); setSize(new Dimension(1024, 800)); setBounds(new Rectangle(getSize())); setPreferredSize(getSize()); setDefaultCloseOperation(DISPOSE_ON_CLOSE); setLayout(new BorderLayout()); this.standalone = isStandalone; addWindowListener(new WindowAdapter() { public void windowClosed(WindowEvent e) { quit(); } }); errorIcon = ActionProducer.getIcon("bullet_error.png", IconSize.SMALL); modifiedIcon = ActionProducer.getIcon("bullet_code_change.png", IconSize.SMALL); skippedIcon = ActionProducer.getIcon("skip.png", IconSize.SMALL); this.glassPane = new InfiniteProgressPanel(); setGlassPane(glassPane); debuggerActions = new ActionProducer(this, serviceUrl); requestResponsePanel = new RequestResponsePanel(this); requestResponsePanel.init(); testPlanChooser = new JComboBox(); testPlanChooser.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent event) { if (event.getItem() != null) { HDTestPlan selected = (HDTestPlan) event.getItem(); if (!selected.equals(currentTestPlan)) { setCurrentTestPlan(selected); } } } }); tankClientChooser = new JComboBox<TankClientChoice>(); debuggerActions.setChoiceComboBoxOptions(tankClientChooser); actionComponents = new ActionComponents(standalone, testPlanChooser, tankClientChooser, debuggerActions); addScriptChangedListener(actionComponents); setJMenuBar(actionComponents.getMenuBar()); Component topPanel = PanelBuilder.createTopPanel(actionComponents); Component bottomPanel = PanelBuilder.createBottomPanel(this); Component contentPanel = PanelBuilder.createContentPanel(this); final JPopupMenu popup = actionComponents.getPopupMenu(); scriptEditorTA.setPopupMenu(null); scriptEditorTA.addMouseListener(new MouseAdapter() { int lastHash; @Override public void mousePressed(MouseEvent e) { maybeShow(e); } @Override public void mouseReleased(MouseEvent e) { maybeShow(e); } private void maybeShow(MouseEvent e) { if (lastHash == getHash(e)) { return; } if (e.isPopupTrigger()) { // select the line try { int offset = scriptEditorTA.viewToModel(e.getPoint()); Rectangle modelToView = scriptEditorTA.modelToView(offset); Point point = new Point(modelToView.x + 1, e.getPoint().y); if (modelToView.contains(point)) { if (!multiSelect) { int line = scriptEditorTA.getLineOfOffset(offset); scriptEditorTA.setCurrentLine(line); } popup.show(e.getComponent(), e.getX(), e.getY()); } } catch (BadLocationException e1) { e1.printStackTrace(); } } else if (e.isShiftDown()) { int line = scriptEditorTA.getCaretLineNumber(); int start = Math.min(line, lastLine); int end = Math.max(line, lastLine); multiSelect = end - start > 1; if (multiSelect) { multiSelectStart = start; multiSelectEnd = end; try { scriptEditorTA.setEnabled(true); scriptEditorTA.select(scriptEditorTA.getLineStartOffset(start), scriptEditorTA.getLineEndOffset(end)); scriptEditorTA.setEnabled(false); } catch (BadLocationException e1) { e1.printStackTrace(); multiSelect = false; } } } else { multiSelect = false; lastLine = scriptEditorTA.getCaretLineNumber(); } lastHash = getHash(e); } private int getHash(MouseEvent e) { return new HashCodeBuilder().append(e.getButton()).append(e.getSource().hashCode()) .append(e.getPoint()).toHashCode(); } }); JSplitPane mainSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT); mainSplit.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); mainSplit.setTopComponent(contentPanel); mainSplit.setBottomComponent(bottomPanel); mainSplit.setDividerLocation(600); mainSplit.setResizeWeight(0.8D); mainSplit.setDividerSize(5); add(topPanel, BorderLayout.NORTH); add(mainSplit, BorderLayout.CENTER); WindowUtil.centerOnScreen(this); pack(); KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); manager.addKeyEventDispatcher(new KeyEventDispatcher() { @Override public boolean dispatchKeyEvent(KeyEvent e) { if (e.getID() == KeyEvent.KEY_PRESSED) { handleKeyEvent(e); } return false; } }); }
From source file:net.sf.jabref.openoffice.OpenOfficePanel.java
private void showSettingsPopup() { JPopupMenu menu = new JPopupMenu(); final JCheckBoxMenuItem autoSync = new JCheckBoxMenuItem( Localization.lang("Automatically sync bibliography when inserting citations"), Globals.prefs.getBoolean(JabRefPreferences.SYNC_OO_WHEN_CITING)); final JRadioButtonMenuItem useActiveBase = new JRadioButtonMenuItem( Localization.lang("Look up BibTeX entries in the active tab only")); final JRadioButtonMenuItem useAllBases = new JRadioButtonMenuItem( Localization.lang("Look up BibTeX entries in all open databases")); final JMenuItem clearConnectionSettings = new JMenuItem(Localization.lang("Clear connection settings")); ButtonGroup bg = new ButtonGroup(); bg.add(useActiveBase);// w ww . j av a2s . co m bg.add(useAllBases); if (Globals.prefs.getBoolean(JabRefPreferences.USE_ALL_OPEN_BASES)) { useAllBases.setSelected(true); } else { useActiveBase.setSelected(true); } autoSync.addActionListener( e -> Globals.prefs.putBoolean(JabRefPreferences.SYNC_OO_WHEN_CITING, autoSync.isSelected())); useAllBases.addActionListener( e -> Globals.prefs.putBoolean(JabRefPreferences.USE_ALL_OPEN_BASES, useAllBases.isSelected())); useActiveBase.addActionListener( e -> Globals.prefs.putBoolean(JabRefPreferences.USE_ALL_OPEN_BASES, !useActiveBase.isSelected())); clearConnectionSettings.addActionListener(e -> { Globals.prefs.clear(JabRefPreferences.OO_PATH); Globals.prefs.clear(JabRefPreferences.OO_EXECUTABLE_PATH); Globals.prefs.clear(JabRefPreferences.OO_JARS_PATH); frame.output(Localization.lang("Cleared connection settings.")); }); menu.add(autoSync); menu.addSeparator(); menu.add(useActiveBase); menu.add(useAllBases); menu.addSeparator(); menu.add(clearConnectionSettings); menu.show(settingsB, 0, settingsB.getHeight()); }
From source file:ca.sqlpower.swingui.object.VariablesPanel.java
@SuppressWarnings("unchecked") private void showVarsPicker() { final MultiValueMap namespaces = this.variableHelper.getNamespaces(); List<String> sortedNames = new ArrayList<String>(namespaces.keySet().size()); sortedNames.addAll(namespaces.keySet()); Collections.sort(sortedNames, new Comparator<String>() { public int compare(String o1, String o2) { if (o1 == null) { return -1; }/*from w ww . ja va2s.c om*/ if (o2 == null) { return 1; } return o1.compareTo(o2); }; }); final JPopupMenu menu = new JPopupMenu(); for (final String name : sortedNames) { final JMenu subMenu = new JMenu(name); menu.add(subMenu); subMenu.addMenuListener(new MenuListener() { private Timer timer; public void menuSelected(MenuEvent e) { subMenu.removeAll(); subMenu.add(new PleaseWaitAction()); ActionListener menuPopulator = new ActionListener() { public void actionPerformed(ActionEvent e) { if (subMenu.isPopupMenuVisible()) { subMenu.removeAll(); for (Object namespaceO : namespaces.getCollection(name)) { String namespace = (String) namespaceO; logger.debug("Resolving variables for namespace ".concat(namespace)); int nbItems = 0; for (String key : variableHelper.keySet(namespace)) { subMenu.add(new InsertVariableAction(SPVariableHelper.getKey((String) key), (String) key)); nbItems++; } if (nbItems == 0) { subMenu.add(new DummyAction()); logger.debug("No variables found."); } } subMenu.revalidate(); subMenu.getPopupMenu().pack(); } } }; timer = new Timer(700, menuPopulator); timer.setRepeats(false); timer.start(); } public void menuDeselected(MenuEvent e) { timer.stop(); } public void menuCanceled(MenuEvent e) { timer.stop(); } }); } menu.show(varNameText, 0, varNameText.getHeight()); }