Example usage for javax.swing JPopupMenu show

List of usage examples for javax.swing JPopupMenu show

Introduction

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

Prototype

public void show(Component invoker, int x, int y) 

Source Link

Document

Displays the popup menu at the position x,y in the coordinate space of the component invoker.

Usage

From source file:PopUpColorMenu.java

public PopUpColorMenu() {
    JFrame frame = new JFrame();

    final JPopupMenu colorMenu = new JPopupMenu("Color");
    colorMenu.add(makeMenuItem("Red"));
    colorMenu.add(makeMenuItem("Green"));
    colorMenu.add(makeMenuItem("Blue"));

    MouseListener mouseListener = new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
            checkPopup(e);//from  w ww.j  a  v a  2s.c  o m
        }

        public void mouseClicked(MouseEvent e) {
            checkPopup(e);
        }

        public void mouseReleased(MouseEvent e) {
            checkPopup(e);
        }

        private void checkPopup(MouseEvent e) {
            if (e.isPopupTrigger()) {
                selectedComponent = e.getComponent();
                colorMenu.show(e.getComponent(), e.getX(), e.getY());
            }
        }
    };

    frame.setLayout(new FlowLayout());
    JButton button = new JButton("Uno");
    button.addMouseListener(mouseListener);
    frame.add(button);
    button = new JButton("Due");
    button.addMouseListener(mouseListener);
    frame.add(button);
    button = new JButton("Tre");
    button.addMouseListener(mouseListener);
    frame.add(button);

    frame.getContentPane().addMouseListener(mouseListener);

    frame.setSize(200, 50);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

From source file:net.sf.jabref.gui.maintable.MainTableSelectionListener.java

/**
 * Method to handle a single left click on one the special fields (e.g., ranking, quality, ...)
 * Shows either a popup to select/clear a value or simply toggles the functionality to set/unset the special field
 *
 * @param e MouseEvent used to determine the position of the popups
 * @param columnName the name of the specialfield column
 */// w w  w .ja  v  a  2s .c  om
private void handleSpecialFieldLeftClick(MouseEvent e, String columnName) {
    if ((e.getClickCount() == 1)) {
        SpecialFieldsUtils.getSpecialFieldInstanceFromFieldName(columnName).ifPresent(field -> {
            // special field found
            if (field.isSingleValueField()) {
                // directly execute toggle action instead of showing a menu with one action
                field.getValues().get(0).getAction(panel.frame()).action();
            } else {
                JPopupMenu menu = new JPopupMenu();
                for (SpecialFieldValue val : field.getValues()) {
                    menu.add(val.getMenuAction(panel.frame()));
                }
                menu.show(table, e.getX(), e.getY());
            }
        });
    }
}

From source file:com.mirth.connect.client.ui.components.MirthTable.java

public MirthTable(String prefix, Set<String> defaultVisibleColumns) {
    super();/*  ww w  .ja  v  a2s .co  m*/

    this.prefix = prefix;
    this.defaultVisibleColumns = defaultVisibleColumns;

    userPreferences = Preferences.userNodeForPackage(Mirth.class);
    columnOrderMap = new HashMap<String, Integer>();
    if (StringUtils.isNotEmpty(prefix)) {
        try {
            userPreferences = Preferences.userNodeForPackage(Mirth.class);
            String columns = userPreferences.get(prefix + "ColumnOrderMap", "");

            if (StringUtils.isNotEmpty(columns)) {
                columnOrderMap = (Map<String, Integer>) ObjectXMLSerializer.getInstance().deserialize(columns,
                        Map.class);
            }
        } catch (Exception e) {
        }

        sortKeys = new ArrayList<SortKey>();
        try {
            String sortOrder = userPreferences.get(prefix + "SortOrder", "");

            if (StringUtils.isNotEmpty(sortOrder)) {
                sortKeys = ObjectXMLSerializer.getInstance().deserialize(sortOrder, List.class);
            }
        } catch (Exception e) {
        }
    }

    setDragEnabled(true);
    addKeyListener(new KeyListener() {

        public void keyPressed(KeyEvent e) {
            boolean isAccelerated = (((e.getModifiers()
                    & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) > 0)
                    || ((e.getModifiers() & InputEvent.CTRL_MASK) > 0));
            if ((e.getKeyCode() == KeyEvent.VK_S) && isAccelerated) {
                PlatformUI.MIRTH_FRAME.doContextSensitiveSave();
            }
        }

        public void keyReleased(KeyEvent e) {
        }

        public void keyTyped(KeyEvent e) {
        }
    });

    /*
     * Swingx 1.0 has this set to true by default, which doesn't allow dragging and dropping
     * into tables. Swingx 0.8 had this set to false. Tables that want it set to true can
     * override it.
     */
    putClientProperty("terminateEditOnFocusLost", Boolean.FALSE);

    getTableHeader().addMouseListener(new MouseAdapter() {
        public void mouseReleased(MouseEvent e) {
            saveColumnOrder();
        }
    });

    final JButton columnControlButton = new JButton(new ColumnControlButton(this).getIcon());

    columnControlButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JPopupMenu columnMenu = getColumnMenu();
            Dimension buttonSize = columnControlButton.getSize();
            int xPos = columnControlButton.getComponentOrientation().isLeftToRight()
                    ? buttonSize.width - columnMenu.getPreferredSize().width
                    : 0;
            columnMenu.show(columnControlButton, xPos, columnControlButton.getHeight());
        }
    });

    setColumnControl(columnControlButton);
}

From source file:lu.lippmann.cdb.ext.hydviga.ui.SimilarCasesFrame.java

/**
 * Constructor.// w  w w  . j a v  a  2 s  .  c o  m
 */
SimilarCasesFrame(final Instances ds, final int dateIdx, final StationsDataProvider gcp, String attrname,
        final int gapsize, final int position, final double x, final double y, final int year,
        final String season, final boolean isDuringRising) throws Exception {
    LogoHelper.setLogo(this);
    this.setTitle("KnowledgeDB: Suggested configurations / similar cases");

    this.inputCaseTablePanel = new JXPanel();
    this.inputCaseTablePanel.setBorder(new TitledBorder("Present case"));
    this.inputCaseChartPanel = new JXPanel();
    this.inputCaseChartPanel.setBorder(new TitledBorder("Profile of the present case"));
    this.outputCasesTablePanel = new JXPanel();
    this.outputCasesTablePanel.setBorder(new TitledBorder("Suggested cases"));
    this.outputCasesChartPanel = new JXPanel();
    this.outputCasesChartPanel.setBorder(new TitledBorder("Profile of the selected suggested case"));

    getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS));
    getContentPane().add(inputCaseTablePanel);
    getContentPane().add(inputCaseChartPanel);
    getContentPane().add(outputCasesTablePanel);
    getContentPane().add(outputCasesChartPanel);

    final Instances res = GapFillingKnowledgeDB.findSimilarCases(attrname, x, y, year, season, gapsize,
            position, isDuringRising, gcp.findDownstreamStation(attrname) != null,
            gcp.findUpstreamStation(attrname) != null,
            GapsUtil.measureHighMiddleLowInterval(ds, ds.attribute(attrname).index(), position - 1));

    final Instances inputCase = new Instances(res);
    while (inputCase.numInstances() > 1)
        inputCase.remove(1);
    final JXTable inputCaseTable = buidJXTable(inputCase);
    final JScrollPane inputScrollPane = new JScrollPane(inputCaseTable);
    //System.out.println(inputScrollPane.getPreferredSize());
    inputScrollPane.setPreferredSize(
            new Dimension(COMPONENT_WIDTH, (int) (50 + inputScrollPane.getPreferredSize().getHeight())));
    this.inputCaseTablePanel.add(inputScrollPane);

    final ChartPanel inputcp = GapsUIUtil.buildGapChartPanel(ds, dateIdx, ds.attribute(attrname), gapsize,
            position);
    inputcp.getChart().removeLegend();
    inputcp.setPreferredSize(CHART_DIMENSION);
    this.inputCaseChartPanel.add(inputcp);

    final Instances outputCases = new Instances(res);
    outputCases.remove(0);
    final JXTable outputCasesTable = buidJXTable(outputCases);
    final JScrollPane outputScrollPane = new JScrollPane(outputCasesTable);
    outputScrollPane.setPreferredSize(
            new Dimension(COMPONENT_WIDTH, (int) (50 + outputScrollPane.getPreferredSize().getHeight())));
    this.outputCasesTablePanel.add(outputScrollPane);

    outputCasesTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    outputCasesTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                final int modelRow = outputCasesTable.getSelectedRow();

                final String attrname = outputCasesTable.getModel().getValueAt(modelRow, 1).toString();
                final int gapsize = (int) Double
                        .valueOf(outputCasesTable.getModel().getValueAt(modelRow, 4).toString()).doubleValue();
                final int position = (int) Double
                        .valueOf(outputCasesTable.getModel().getValueAt(modelRow, 5).toString()).doubleValue();

                try {
                    final ChartPanel cp = GapsUIUtil.buildGapChartPanel(ds, dateIdx, ds.attribute(attrname),
                            gapsize, position);
                    cp.getChart().removeLegend();
                    cp.setPreferredSize(CHART_DIMENSION);
                    outputCasesChartPanel.removeAll();
                    outputCasesChartPanel.add(cp);
                    getContentPane().repaint();
                    pack();
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        }
    });

    outputCasesTable.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(final MouseEvent e) {
            final InstanceTableModel instanceTableModel = (InstanceTableModel) outputCasesTable.getModel();
            final int row = outputCasesTable.rowAtPoint(e.getPoint());
            final int modelRow = outputCasesTable.convertRowIndexToModel(row);

            final String attrname = instanceTableModel.getValueAt(modelRow, 1).toString();
            final int gapsize = (int) Double.valueOf(instanceTableModel.getValueAt(modelRow, 4).toString())
                    .doubleValue();
            final int position = (int) Double.valueOf(instanceTableModel.getValueAt(modelRow, 5).toString())
                    .doubleValue();

            if (e.isPopupTrigger()) {
                final JPopupMenu jPopupMenu = new JPopupMenu("feur");

                final JMenuItem mi = new JMenuItem("Use this configuration");
                mi.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(final ActionEvent e) {
                        System.out.println("not implemented!");
                    }
                });
                jPopupMenu.add(mi);
                jPopupMenu.show(outputCasesTable, e.getX(), e.getY());
            } else {
                // nothing?
            }
        }
    });

    setPreferredSize(new Dimension(FRAME_WIDTH, 900));

    pack();
    setVisible(true);

    /* select the first row */
    outputCasesTable.setRowSelectionInterval(0, 0);
}

From source file:ucar.unidata.idv.control.chart.ChartHolder.java

/**
 * show popup//  w  ww.  j a  v a  2s. co  m
 *
 * @param event event
 */
private void showPopupMenu(MouseEvent event) {
    List items = new ArrayList();
    getMenuItems(items);
    JPopupMenu popupMenu = GuiUtils.makePopupMenu(items);
    popupMenu.show(chartPanel, event.getX(), event.getY());
}

From source file:biz.wolschon.finance.jgnucash.accountProperties.AccountProperties.java

/**
 * {@inheritDoc}// ww w. ja  v a 2s . c  o  m
 */
@Override
public void actionPerformed(final ActionEvent aE) {
    JPanel newPanel = new JPanel(new GridLayout(2, 2));

    newPanel.add(new JLabel("GUID:"));
    final JTextField disabledIDInput = new JTextField(myAccount.getId());
    final JPopupMenu accountIDPopupMenu = createAccountIDPopupMenu();
    disabledIDInput.setEditable(false);
    disabledIDInput.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseReleased(final MouseEvent arg0) {
            if (arg0.isPopupTrigger()) {
                accountIDPopupMenu.show(disabledIDInput, arg0.getX(), arg0.getY());
            }
        }

        @Override
        public void mousePressed(final MouseEvent arg0) {
            if (arg0.isPopupTrigger()) {
                accountIDPopupMenu.show(disabledIDInput, arg0.getX(), arg0.getY());
            }
        }

    });
    newPanel.add(disabledIDInput);

    newPanel.add(new JLabel("name:"));
    final JTextField nameInput = new JTextField(myAccount.getName());
    nameInput.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent aE) {
            myAccount.setName(nameInput.getText());
        }

    });
    newPanel.add(nameInput);

    myFrame = new JFrame(myAccount.getName());
    myFrame.getContentPane().setLayout(new BorderLayout());
    myFrame.getContentPane().add(newPanel, BorderLayout.NORTH);
    myFrame.getContentPane().add(getButtonsPanel(), BorderLayout.SOUTH);

    myFrame.getContentPane().add(getMySettingsPanel(), BorderLayout.CENTER);
    myFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    myFrame.pack();
    myFrame.setVisible(true);
}

From source file:CubaHSQLDBServer.java

private void addCopyPopup(final JTextArea source) {
    final JPopupMenu popup = new JPopupMenu();
    popup.add(new AbstractAction("Copy to clipboard") {
        @Override//w  w w  .  j a  v  a 2 s . co  m
        public void actionPerformed(ActionEvent e) {
            StringSelection contents = new StringSelection(source.getText());
            Toolkit.getDefaultToolkit().getSystemClipboard().setContents(contents, contents);
        }
    });
    source.add(popup);
    source.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
            if (e.isPopupTrigger()) {
                popup.show(source, e.getX(), e.getY());
            }
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            if (e.isPopupTrigger()) {
                popup.show(source, e.getX(), e.getY());
            }
        }
    });
}

From source file:net.sf.jabref.gui.MainTableSelectionListener.java

@Override
public void mouseClicked(MouseEvent e) {

    // First find the column on which the user has clicked.
    final int col = table.columnAtPoint(e.getPoint());
    final int row = table.rowAtPoint(e.getPoint());

    // A double click on an entry should open the entry's editor.
    if (e.getClickCount() == 2) {

        BibtexEntry toShow = tableRows.get(row);
        editSignalled(toShow);/*ww w .ja  v a2  s. c o m*/
    }

    // Check if the user has clicked on an icon cell to open url or pdf.
    final String[] iconType = table.getIconTypeForColumn(col);

    // Workaround for Windows. Right-click is not popup trigger on mousePressed, but
    // on mouseReleased. Therefore we need to avoid taking action at this point, because
    // action will be taken when the button is released:
    if (OS.WINDOWS && (iconType != null) && (e.getButton() != MouseEvent.BUTTON1)) {
        return;
    }

    if (iconType != null) {
        // left click on icon field
        SpecialField field = SpecialFieldsUtils.getSpecialFieldInstanceFromFieldName(iconType[0]);
        if ((e.getClickCount() == 1) && (field != null)) {
            // special field found
            if (field.isSingleValueField()) {
                // directly execute toggle action instead of showing a menu with one action
                field.getValues().get(0).getAction(panel.frame()).action();
            } else {
                JPopupMenu menu = new JPopupMenu();
                for (SpecialFieldValue val : field.getValues()) {
                    menu.add(val.getMenuAction(panel.frame()));
                }
                menu.show(table, e.getX(), e.getY());
            }
            return;
        }

        Object value = table.getValueAt(row, col);
        if (value == null) {
            return; // No icon here, so we do nothing.
        }

        final BibtexEntry entry = tableRows.get(row);

        // Get the icon type. Corresponds to the field name.
        int hasField = -1;
        for (int i = iconType.length - 1; i >= 0; i--) {
            if (entry.getField(iconType[i]) != null) {
                hasField = i;
            }
        }
        if (hasField == -1) {
            return;
        }
        final String fieldName = iconType[hasField];

        //If this is a file link field with specified file types,
        //we should also pass the types.
        String[] fileTypes = {};
        if ((hasField == 0) && iconType[hasField].equals(Globals.FILE_FIELD) && (iconType.length > 1)) {
            fileTypes = iconType;
        }
        final List<String> listOfFileTypes = Collections.unmodifiableList(Arrays.asList(fileTypes));

        // Open it now. We do this in a thread, so the program won't freeze during the wait.
        JabRefExecutorService.INSTANCE.execute(new Runnable() {

            @Override
            public void run() {
                panel.output(Localization.lang("External viewer called") + '.');

                Object link = entry.getField(fieldName);
                if (link == null) {
                    LOGGER.info("Error: no link to " + fieldName + '.');
                    return; // There is an icon, but the field is not set.
                }

                // See if this is a simple file link field, or if it is a file-list
                // field that can specify a list of links:
                if (fieldName.equals(Globals.FILE_FIELD)) {

                    // We use a FileListTableModel to parse the field content:
                    FileListTableModel fileList = new FileListTableModel();
                    fileList.setContent((String) link);

                    FileListEntry flEntry = null;
                    // If there are one or more links of the correct type,
                    // open the first one:
                    if (!listOfFileTypes.isEmpty()) {
                        for (int i = 0; i < fileList.getRowCount(); i++) {
                            flEntry = fileList.getEntry(i);
                            boolean correctType = false;
                            for (String listOfFileType : listOfFileTypes) {
                                if (flEntry.getType().toString().equals(listOfFileType)) {
                                    correctType = true;
                                }
                            }
                            if (correctType) {
                                break;
                            }
                            flEntry = null;
                        }
                    }
                    //If there are no file types specified, consider all files.
                    else if (fileList.getRowCount() > 0) {
                        flEntry = fileList.getEntry(0);
                    }
                    if (flEntry != null) {
                        //                            if (fileList.getRowCount() > 0) {
                        //                                FileListEntry flEntry = fileList.getEntry(0);

                        ExternalFileMenuItem item = new ExternalFileMenuItem(panel.frame(), entry, "",
                                flEntry.getLink(), flEntry.getType().getIcon(), panel.metaData(),
                                flEntry.getType());
                        boolean success = item.openLink();
                        if (!success) {
                            panel.output(Localization.lang("Unable to open link."));
                        }
                    }
                } else {
                    try {
                        JabRefDesktop.openExternalViewer(panel.metaData(), (String) link, fieldName);
                    } catch (IOException ex) {
                        panel.output(Localization.lang("Unable to open link."));
                    }

                    /*ExternalFileType type = Globals.prefs.getExternalFileTypeByMimeType("text/html");
                    ExternalFileMenuItem item = new ExternalFileMenuItem
                        (panel.frame(), entry, "",
                        (String)link, type.getIcon(),
                        panel.metaData(), type);
                    boolean success = item.openLink();
                    if (!success) {
                    panel.output(Localization.lang("Unable to open link."));
                    } */
                    //Util.openExternalViewer(panel.metaData(), (String)link, fieldName);
                }

                //catch (IOException ex) {
                //    panel.output(Globals.lang("Error") + ": " + ex.getMessage());
                //}
            }

        });
    }
}

From source file:MouseTest.java

public MouseTest() {
    super();/*from   w w  w  .j  av  a  2s  . c o  m*/

    final JPopupMenu pop = new JPopupMenu();
    pop.add(new JMenuItem("Cut"));
    pop.add(new JMenuItem("Copy"));
    pop.add(new JMenuItem("Paste"));
    pop.addSeparator();
    pop.add(new JMenuItem("Select All"));
    pop.setInvoker(this);

    MouseListener popup = new MouseListener() {
        public void mouseClicked(MouseEvent e) {
        }

        public void mouseEntered(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
        }

        public void mousePressed(MouseEvent e) {
            if (e.isPopupTrigger()) {
                showPopup(e);
            }
        }

        public void mouseReleased(MouseEvent e) {
            if (e.isPopupTrigger()) {
                showPopup(e);
            }
        }

        private void showPopup(MouseEvent e) {
            pop.show(e.getComponent(), e.getX(), e.getY());
        }
    };
    addMouseListener(popup);

    MouseListener drawing1 = new MouseListener() {
        public void mouseClicked(MouseEvent e) {
        }

        public void mouseEntered(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
        }

        public void mousePressed(MouseEvent e) {
            color = Color.RED;
            startX = endX = e.getX();
            startY = endY = e.getY();
            repaint();
        }

        public void mouseReleased(MouseEvent e) {
            color = Color.BLACK;
            repaint();
        }
    };
    addMouseListener(drawing1);

    MouseMotionListener drawing2 = new MouseMotionListener() {
        public void mouseDragged(MouseEvent e) {
            endX = e.getX();
            endY = e.getY();
            repaint();
        }

        public void mouseMoved(MouseEvent e) {
        }
    };
    addMouseMotionListener(drawing2);

}

From source file:jmupen.MyListSelectionListener.java

@Override
public void mousePressed(MouseEvent e) {
    list.setSelectedIndex(list.locationToIndex(e.getPoint()));
    int index = list.getSelectedIndex();
    if (SwingUtilities.isRightMouseButton(e)) {
        JPopupMenu menu = new JPopupMenu();
        JMenuItem item = new JMenuItem("Remove");
        item.addActionListener(new ActionListener() {
            @Override// w w  w .  j a va2  s .c om
            public void actionPerformed(ActionEvent e) {
                if (index != -1) {
                    try {
                        System.out.println("Linea: " + index + " " + model.get(index));
                        model.removeElementAt(index);
                        removeLines(index, JMupenUtils.getRecents().toFile());
                        JMupenUtils.setGames(JMupenUtils.getGamesFromFile(JMupenUtils.getRecents()));
                    } catch (IOException ex) {
                        System.err.println("Error removing recent game. " + ex.getLocalizedMessage());
                    }
                }
            }
        });
        menu.add(item);
        menu.show(list, e.getX(), e.getY());
    }
}