javaswingjmenuitem

jpopupmenu menuitem actionperformed not triggered


The popupmenu and menuitem show up fine, but I can't find out why When I click on the menuitem, nothing happen, not even a simple println. what am I missing?

here's my code :

private void jLabel33MouseReleased(java.awt.event.MouseEvent evt) {                                       
        Component source = (Component) evt.getSource();
        Component panelSource = source.getParent().getParent().getParent().getParent().getParent();
        if (SwingUtilities.isRightMouseButton(evt)){

            ModelLigneModifier ligne = (ModelLigneModifier) SwingUtilities.getAncestorOfClass(ModelLigneModifier.class, (Component) evt.getSource());
            ligne.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 0, 0), 4));
            JPopupMenu menu = new JPopupMenu();
            JMenuItem modifier = new JMenuItem("Modifier le prix");
            modifier.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Controleur.supprimerLigne(panelSource, ligneCompte);
                    System.out.println("modifier");
                }
            });
            JMenuItem supprimer = new JMenuItem("Supprimer la ligne");
            supprimer.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Controleur.modifierLigne(panelSource, ligneCompte);
                    System.out.println("modifier");
                }
            });
            menu.add(new JMenuItem("Modifier le prix"));
            menu.add(new JMenuItem("Supprimer la ligne"));
            //ligne.setComponentPopupMenu(menu);
            menu.show(ligne, evt.getX(), evt.getY());

        }
        else{
        Controleur.ajouterLigneCompte(panelSource);
        }

    } 

Solution

  • When I click on the menuitem, nothing happen, not even a simple println.

    You create a JMenuItem and add an ActionListener to it, which is correct:

    JMenuItem modifier = new JMenuItem("Modifier le prix");
    modifier.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            Controleur.supprimerLigne(panelSource, ligneCompte);
            System.out.println("modifier");
        }
    });
    

    But then you add a new menu item without an ActionListener to the popup menu, which is incorrect:

    menu.add(new JMenuItem("Modifier le prix"));
    

    The code should be:

    //menu.add(new JMenuItem("Modifier le prix"));
    menu.add( modifier );