Example usage for javax.swing JPopupMenu addPopupMenuListener

List of usage examples for javax.swing JPopupMenu addPopupMenuListener

Introduction

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

Prototype

public void addPopupMenuListener(PopupMenuListener l) 

Source Link

Document

Adds a PopupMenu listener.

Usage

From source file:MainClass.java

public static void main(String[] a) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    ActionListener actionListener = new PopupActionListener();
    PopupMenuListener popupMenuListener = new MyPopupMenuListener();

    JPopupMenu popupMenu = new JPopupMenu("Title");
    popupMenu.addPopupMenuListener(popupMenuListener);

    JMenuItem cutMenuItem = new JMenuItem("Cut");
    cutMenuItem.addActionListener(actionListener);
    popupMenu.add(cutMenuItem);//from  w  w  w.j a  v a  2s . c  om

    JMenuItem copyMenuItem = new JMenuItem("Copy");
    copyMenuItem.addActionListener(actionListener);
    popupMenu.add(copyMenuItem);

    JMenuItem pasteMenuItem = new JMenuItem("Paste");
    pasteMenuItem.addActionListener(actionListener);
    pasteMenuItem.setEnabled(false);
    popupMenu.add(pasteMenuItem);

    popupMenu.addSeparator();

    JMenuItem findMenuItem = new JMenuItem("Find");
    findMenuItem.addActionListener(actionListener);
    popupMenu.add(findMenuItem);
    JButton label = new JButton();
    frame.add(label);
    label.setComponentPopupMenu(popupMenu);

    frame.setSize(350, 250);
    frame.setVisible(true);
}

From source file:PopupSample.java

public static void main(String args[]) {
    ActionListener actionListener = new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            System.out.println("Selected: " + actionEvent.getActionCommand());
        }/* ww  w. ja  v a2s.  c  o m*/
    };

    PopupMenuListener popupMenuListener = new PopupMenuListener() {
        public void popupMenuCanceled(PopupMenuEvent popupMenuEvent) {
            System.out.println("Canceled");
        }

        public void popupMenuWillBecomeInvisible(PopupMenuEvent popupMenuEvent) {
            System.out.println("Becoming Invisible");
        }

        public void popupMenuWillBecomeVisible(PopupMenuEvent popupMenuEvent) {
            System.out.println("Becoming Visible");
        }
    };

    JFrame frame = new JFrame("Popup Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPopupMenu popupMenu = new JPopupMenu();
    popupMenu.addPopupMenuListener(popupMenuListener);

    JMenuItem cutMenuItem = new JMenuItem("Cut");
    cutMenuItem.addActionListener(actionListener);
    popupMenu.add(cutMenuItem);

    JMenuItem copyMenuItem = new JMenuItem("Copy");
    copyMenuItem.addActionListener(actionListener);
    popupMenu.add(copyMenuItem);

    JMenuItem pasteMenuItem = new JMenuItem("Paste");
    pasteMenuItem.addActionListener(actionListener);
    pasteMenuItem.setEnabled(false);
    popupMenu.add(pasteMenuItem);

    popupMenu.addSeparator();

    JMenuItem findMenuItem = new JMenuItem("Find");
    findMenuItem.addActionListener(actionListener);
    popupMenu.add(findMenuItem);

    MouseListener mouseListener = new JPopupMenuShower(popupMenu);
    frame.addMouseListener(mouseListener);

    frame.setSize(350, 250);
    frame.setVisible(true);
}

From source file:MyPopupMenuListener.java

public static void main(final String args[]) {
    JFrame frame = new JFrame("Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPopupMenu popupMenu = new JPopupMenu("Title");
    PopupMenuListener popupMenuListener = new MyPopupMenuListener();

    popupMenu.addPopupMenuListener(popupMenuListener);

    JMenuItem cutMenuItem = new JMenuItem("Cut");
    popupMenu.add(cutMenuItem);/*w ww  .  j  av a  2 s.  com*/

    JMenuItem copyMenuItem = new JMenuItem("Copy");
    popupMenu.add(copyMenuItem);

    JMenuItem pasteMenuItem = new JMenuItem("Paste");
    pasteMenuItem.setEnabled(false);
    popupMenu.add(pasteMenuItem);

    popupMenu.addSeparator();

    JMenuItem findMenuItem = new JMenuItem("Find");
    popupMenu.add(findMenuItem);
    JButton label = new JButton();
    frame.add(label);
    label.setComponentPopupMenu(popupMenu);

    frame.setSize(350, 250);
    frame.setVisible(true);
}

From source file:MyPopupMenuListener.java

public static void main(final String args[]) {
    JFrame frame = new JFrame("PopupSample Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Create popup menu, attach popup menu listener
    JPopupMenu popupMenu = new JPopupMenu("Title");
    PopupMenuListener popupMenuListener = new MyPopupMenuListener();

    popupMenu.addPopupMenuListener(popupMenuListener);

    // Cut//www.j a va2s .  co  m
    JMenuItem cutMenuItem = new JMenuItem("Cut");
    popupMenu.add(cutMenuItem);

    // Copy
    JMenuItem copyMenuItem = new JMenuItem("Copy");
    popupMenu.add(copyMenuItem);
    // Paste
    JMenuItem pasteMenuItem = new JMenuItem("Paste");
    pasteMenuItem.setEnabled(false);
    popupMenu.add(pasteMenuItem);

    // Separator
    popupMenu.addSeparator();

    // Find
    JMenuItem findMenuItem = new JMenuItem("Find");
    popupMenu.add(findMenuItem);
    JButton label = new JButton();
    frame.add(label);
    label.setComponentPopupMenu(popupMenu);

    frame.setSize(350, 250);
    frame.setVisible(true);
}

From source file:MediumPopupMenuSample.java

public static void main(String args[]) {
    // Define ActionListener
    ActionListener aListener = new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            System.out.println("Selected: " + event.getActionCommand());
        }//from   ww  w .j  a va  2s.  com
    };

    // Define PopupMenuListener
    PopupMenuListener pListener = new PopupMenuListener() {
        public void popupMenuCanceled(PopupMenuEvent event) {
            System.out.println("Canceled");
        }

        public void popupMenuWillBecomeInvisible(PopupMenuEvent event) {
            System.out.println("Becoming Invisible");
        }

        public void popupMenuWillBecomeVisible(PopupMenuEvent event) {
            System.out.println("Becoming Visible");
        }
    };

    // Define
    JFrame frame = new JFrame("Popup Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPopupMenu.setDefaultLightWeightPopupEnabled(false);

    // Create popup menu, attach popup menu listener
    final JPopupMenu popupMenu = new JPopupMenu();
    popupMenu.addPopupMenuListener(pListener);

    // Cut
    JMenuItem cutItem = new JMenuItem("Cut");
    cutItem.addActionListener(aListener);
    popupMenu.add(cutItem);

    // Copy
    JMenuItem copyItem = new JMenuItem("Copy");
    copyItem.addActionListener(aListener);
    popupMenu.add(copyItem);

    // Paste
    JMenuItem pasteItem = new JMenuItem("Paste");
    pasteItem.addActionListener(aListener);
    pasteItem.setEnabled(false);
    popupMenu.add(pasteItem);

    // Separator
    popupMenu.addSeparator();

    // Find
    JMenuItem findItem = new JMenuItem("Find");
    findItem.addActionListener(aListener);
    popupMenu.add(findItem);

    // Enable showing
    MouseListener mouseListener = new JPopupMenuShower(popupMenu);
    frame.addMouseListener(mouseListener);

    Button button = new Button("Label");
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.out.println(popupMenu.isLightWeightPopupEnabled());
        }
    });
    frame.getContentPane().add(button, BorderLayout.SOUTH);

    frame.setSize(350, 250);
    frame.setVisible(true);
}

From source file:cz.muni.fi.javaseminar.kafa.bookregister.gui.MainWindow.java

private void initBooksTable() {
    booksTable.getColumnModel().getColumn(2)
            .setCellEditor(new DatePickerCellEditor(new SimpleDateFormat("dd. MM. yyyy")));
    booksTable.getColumnModel().getColumn(2).setCellRenderer(new DefaultTableCellRenderer() {

        @Override//from w  w w  . j a v  a 2 s. c o m
        public Component getTableCellRendererComponent(JTable jtable, Object value, boolean selected,
                boolean hasFocus, int row, int column) {

            if (value instanceof Date) {

                // You could use SimpleDateFormatter instead
                value = new SimpleDateFormat("dd. MM. yyyy").format(value);

            }

            return super.getTableCellRendererComponent(jtable, value, selected, hasFocus, row, column);

        }
    });
    booksTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    JPopupMenu booksPopupMenu = new JPopupMenu();
    JMenuItem deleteBook = new JMenuItem("Delete");
    booksPopupMenu.addPopupMenuListener(new PopupMenuListener() {

        @Override
        public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    int rowAtPoint = booksTable.rowAtPoint(
                            SwingUtilities.convertPoint(booksPopupMenu, new Point(0, 0), booksTable));
                    if (rowAtPoint > -1) {
                        booksTable.setRowSelectionInterval(rowAtPoint, rowAtPoint);
                    }
                }
            });
        }

        @Override
        public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void popupMenuCanceled(PopupMenuEvent e) {
            // TODO Auto-generated method stub

        }
    });
    deleteBook.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (booksTable.getSelectedRow() == -1) {
                JOptionPane.showMessageDialog(MainWindow.this, "You haven't selected any book.");
                return;
            }
            Book book = booksTableModel.getBooks().get(booksTable.getSelectedRow());
            new SwingWorker<Void, Void>() {

                @Override
                protected Void doInBackground() throws Exception {
                    log.debug("Deleting book: " + book.getName() + " from database.");
                    bookManager.deleteBook(book);
                    return null;
                }

                @Override
                protected void done() {
                    try {
                        get();
                    } catch (Exception e) {
                        log.error("There was an exception thrown while deleting a book.", e);
                        return;
                    }

                    updateModel();
                }

            }.execute();

        }
    });
    booksPopupMenu.add(deleteBook);
    booksTable.setComponentPopupMenu(booksPopupMenu);
}

From source file:cz.muni.fi.javaseminar.kafa.bookregister.gui.MainWindow.java

private void initAuthorsTable() {
    authorsTable.getColumnModel().getColumn(2)
            .setCellEditor(new DatePickerCellEditor(new SimpleDateFormat("dd. MM. yyyy")));
    authorsTable.getColumnModel().getColumn(2).setCellRenderer(new DefaultTableCellRenderer() {

        @Override// w  ww  . j  a v  a 2  s  . c o m
        public Component getTableCellRendererComponent(JTable jtable, Object value, boolean selected,
                boolean hasFocus, int row, int column) {

            if (value instanceof Date) {

                // You could use SimpleDateFormatter instead
                value = new SimpleDateFormat("dd. MM. yyyy").format(value);

            }

            return super.getTableCellRendererComponent(jtable, value, selected, hasFocus, row, column);

        }
    });

    authorsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    ListSelectionModel selectionModel = authorsTable.getSelectionModel();
    selectionModel.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            DefaultListSelectionModel source = (DefaultListSelectionModel) e.getSource();
            if (source.getMinSelectionIndex() >= 0) {
                authorsTableModel.setCurrentSlectedIndex(source.getMinSelectionIndex());
            }

            if (!e.getValueIsAdjusting()) {
                booksTableModel.setAuthorIndex(source.getMinSelectionIndex());
            }

        }
    });

    authorsTable.getColumnModel().getColumn(2)
            .setCellEditor(new DatePickerCellEditor(new SimpleDateFormat("dd. MM. yyyy")));
    authorsTable.getColumnModel().getColumn(2).setCellRenderer(new DefaultTableCellRenderer() {

        @Override
        public Component getTableCellRendererComponent(JTable jtable, Object value, boolean selected,
                boolean hasFocus, int row, int column) {

            if (value instanceof Date) {

                // You could use SimpleDateFormatter instead
                value = new SimpleDateFormat("dd. MM. yyyy").format(value);

            }

            return super.getTableCellRendererComponent(jtable, value, selected, hasFocus, row, column);

        }
    });

    JPopupMenu authorsPopupMenu = new JPopupMenu();
    JMenuItem deleteItem = new JMenuItem("Delete");

    authorsPopupMenu.addPopupMenuListener(new PopupMenuListener() {

        @Override
        public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    int rowAtPoint = authorsTable.rowAtPoint(
                            SwingUtilities.convertPoint(authorsPopupMenu, new Point(0, 0), authorsTable));
                    if (rowAtPoint > -1) {
                        authorsTable.setRowSelectionInterval(rowAtPoint, rowAtPoint);
                        authorsTableModel.setCurrentSlectedIndex(rowAtPoint);
                    }
                }
            });
        }

        @Override
        public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void popupMenuCanceled(PopupMenuEvent e) {
            // TODO Auto-generated method stub

        }
    });
    deleteItem.addActionListener(new ActionListener() {
        private Author author;

        @Override
        public void actionPerformed(ActionEvent e) {
            new SwingWorker<Void, Void>() {

                @Override
                protected Void doInBackground() throws Exception {
                    author = authorsTableModel.getAuthors().get(authorsTable.getSelectedRow());
                    log.debug("Deleting author: " + author.getFirstname() + " " + author.getSurname()
                            + " from database.");
                    authorManager.deleteAuthor(author);

                    return null;
                }

                @Override
                protected void done() {
                    try {
                        get();
                    } catch (InterruptedException | ExecutionException e) {
                        if (e.getCause() instanceof DataIntegrityViolationException) {
                            JOptionPane.showMessageDialog(MainWindow.this,
                                    "Couldn't delete author; there are still some books assigned to him.",
                                    "Error", JOptionPane.ERROR_MESSAGE);
                        }
                        log.error("There was an exception thrown during deletion author: "
                                + author.getFirstname() + " " + author.getSurname(), e);

                        return;
                    }

                    updateModel();
                }
            }.execute();
        }
    });
    authorsPopupMenu.add(deleteItem);
    authorsTable.setComponentPopupMenu(authorsPopupMenu);
}

From source file:es.emergya.ui.gis.HistoryMapViewer.java

@Override
protected JPopupMenu getContextMenu() {
    JPopupMenu menu = new JPopupMenu();
    // Centrar aqui
    JMenuItem cent = new JMenuItem(i18n.getString("map.menu.centerHere"), KeyEvent.VK_C);
    cent.setIcon(LogicConstants.getIcon("menucontextual_icon_centrar"));
    cent.addActionListener(new ActionListener() {

        @Override//from  www  .jav  a2s  .c o  m
        public void actionPerformed(ActionEvent e) {
            mapView.zoomToFactor(mapView.getEastNorth(eventOriginal.getX(), eventOriginal.getY()),
                    mapView.zoomFactor);
        }
    });
    menu.add(cent);

    menu.addPopupMenuListener(new PopupMenuListener() {

        @Override
        public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
            eventOriginal = HistoryMapViewer.this.mapView.lastMEvent;
        }

        @Override
        public void popupMenuCanceled(PopupMenuEvent arg0) {
        }

        @Override
        public void popupMenuWillBecomeInvisible(PopupMenuEvent arg0) {
        }
    });
    return menu;
}

From source file:com.igormaznitsa.mindmap.swing.panel.MindMapPanel.java

protected void processPopUp(final Point point, final AbstractElement elementUnderMouse) {
    if (this.controller != null) {
        final ElementPart partUnderMouse = elementUnderMouse == null ? null
                : elementUnderMouse.findPartForPoint(point);

        if (elementUnderMouse != null && !this.selectedTopics.contains(elementUnderMouse.getModel())) {
            this.selectedTopics.clear();
            this.select(elementUnderMouse.getModel(), false);
        }//from   www  .  ja v a  2s .c  om

        final JPopupMenu menu = this.controller.makePopUpForMindMapPanel(this, point, elementUnderMouse,
                partUnderMouse);
        if (menu != null) {

            final MindMapPanel theInstance = this;
            menu.addPopupMenuListener(new PopupMenuListener() {

                @Override
                public void popupMenuWillBecomeVisible(final PopupMenuEvent e) {
                    theInstance.mouseDragSelection = null;
                    theInstance.popupMenuActive = true;
                }

                @Override
                public void popupMenuWillBecomeInvisible(final PopupMenuEvent e) {
                    theInstance.mouseDragSelection = null;
                    theInstance.popupMenuActive = false;
                }

                @Override
                public void popupMenuCanceled(final PopupMenuEvent e) {
                    theInstance.mouseDragSelection = null;
                    theInstance.popupMenuActive = false;
                }
            });

            menu.show(this, point.x, point.y);
        }
    }
}

From source file:es.emergya.ui.gis.FleetControlMapViewer.java

@Override
protected JPopupMenu getContextMenu() {
    JPopupMenu menu = new JPopupMenu();

    menu.setBackground(Color.decode("#E8EDF6"));

    // Ttulo//  w  w  w  .j  av  a2 s.com
    final JMenuItem titulo = new JMenuItem(i18n.getString("map.menu.titulo.puntoGenerico"));
    titulo.setFont(LogicConstants.deriveBoldFont(10.0f));
    titulo.setBackground(Color.decode("#A4A4A4"));
    titulo.setFocusable(false);

    menu.add(titulo);

    menu.addSeparator();

    // Actualizar posicin
    final JMenuItem gps = new JMenuItem(i18n.getString("map.menu.gps"), KeyEvent.VK_P);
    gps.setIcon(LogicConstants.getIcon("menucontextual_icon_actualizargps"));
    menu.add(gps);
    gps.addActionListener(this);
    gps.setEnabled(false);

    menu.addSeparator();

    // Mostrar ms cercanos
    final JMenuItem mmc = new JMenuItem(i18n.getString("map.menu.showNearest"), KeyEvent.VK_M);
    mmc.setIcon(LogicConstants.getIcon("menucontextual_icon_mascercano"));
    mmc.addActionListener(this);
    menu.add(mmc);
    // Centrar aqui
    final JMenuItem cent = new JMenuItem(i18n.getString("map.menu.centerHere"), KeyEvent.VK_C);
    cent.setIcon(LogicConstants.getIcon("menucontextual_icon_centrar"));
    cent.addActionListener(this);
    menu.add(cent);
    // Nueva Incidencia
    final JMenuItem newIncidence = new JMenuItem(i18n.getString("map.menu.newIncidence"), KeyEvent.VK_I);
    newIncidence.setIcon(LogicConstants.getIcon("menucontextual_icon_newIncidence"));
    newIncidence.addActionListener(this);
    menu.add(newIncidence);
    // Calcular ruta desde aqui
    final JMenuItem from = new JMenuItem(i18n.getString("map.menu.route.from"), KeyEvent.VK_D);
    from.setIcon(LogicConstants.getIcon("menucontextual_icon_origenruta"));
    from.addActionListener(this);
    menu.add(from);
    // Calcular ruta hasta aqui
    final JMenuItem to = new JMenuItem(i18n.getString("map.menu.route.to"), KeyEvent.VK_H);
    to.setIcon(LogicConstants.getIcon("menucontextual_icon_destinoruta"));
    to.addActionListener(this);
    menu.add(to);

    menu.addSeparator();

    // Ver ficha [recurso / incidencia]
    final JMenuItem summary = new JMenuItem(i18n.getString("map.menu.summary"), KeyEvent.VK_F);
    summary.setIcon(LogicConstants.getIcon("menucontextual_icon_ficha"));
    summary.addActionListener(this);
    menu.add(summary);
    summary.setEnabled(false);

    menu.addPopupMenuListener(new PopupMenuListener() {

        @SuppressWarnings("unchecked")
        @Override
        public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
            eventOriginal = FleetControlMapViewer.this.mapView.lastMEvent;
            gps.setEnabled(false);
            summary.setEnabled(false);
            titulo.setText(i18n.getString("map.menu.titulo.puntoGenerico"));
            menuObjective = null;
            Point p = new Point(mapView.lastMEvent.getX(), mapView.lastMEvent.getY());
            for (Layer l : mapView.getAllLayers()) { // por cada capa...
                if (l instanceof MarkerLayer) { // ...de marcadores
                    for (Marker marker : ((MarkerLayer) l).data) { // miramos
                        // los
                        // marcadores
                        if ((marker instanceof CustomMarker) && marker.containsPoint(p)) { // y si
                            // estamos
                            // pinchando
                            // en uno
                            CustomMarker m = (CustomMarker) marker;
                            log.trace("Hemos pinchado en " + marker);

                            switch (m.getType()) {
                            case RESOURCE:
                                Recurso r = (Recurso) m.getObject();
                                log.trace("Es un recurso: " + r);
                                if (r != null) {
                                    menuObjective = r;
                                    if (r.getPatrullas() != null) {
                                        titulo.setText(
                                                i18n.getString(Locale.ROOT, "map.menu.titulo.recursoPatrulla",
                                                        r.getIdentificador(), r.getPatrullas()));
                                    } else {
                                        titulo.setText(r.getIdentificador());
                                    }
                                    gps.setEnabled(true);
                                    summary.setEnabled(true);
                                }
                                break;
                            case INCIDENCE:
                                Incidencia i = (Incidencia) m.getObject();
                                log.trace("Es una incidencia: " + i);
                                if (i != null) {
                                    menuObjective = i;
                                    titulo.setText(i.getTitulo());
                                    gps.setEnabled(false);
                                    summary.setEnabled(true);
                                }
                                break;
                            case UNKNOWN:
                                log.trace("Hemos pinchado en un marcador desconocido");
                                break;
                            }

                        }
                    }
                }
            }
        }

        @Override
        public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
        }

        @Override
        public void popupMenuCanceled(PopupMenuEvent e) {
        }
    });

    return menu;
}