Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding JPopupMenu to JPanel

My code:

class PanelGlowny extends JPanel implements ActionListener{}

public class Formatka extends JFrame implements ActionListener{

private JMenuItem klienciMenuItem = new JMenuItem("Klienci");
private JPopupMenu menuPopup = new JPopupMenu();
private PanelGlowny panelGlowny = new PanelGlowny();


public Formatka() {

    add(panelGlowny, BorderLayout.CENTER);
    menuPopup.add(klienciMenuItem);
    panelGlowny.setComponentPopupMenu(menuPopup);


   }
}

And i do not see popupmenu when i click right button on mouse. Why?

like image 945
user1304098 Avatar asked Dec 21 '22 21:12

user1304098


1 Answers

Works for me when added to a JPanel.

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;

public class Formatka extends JPanel {

    private JMenuItem klienciMenuItem = new JMenuItem("Klienci");
    private JPopupMenu menuPopup = new JPopupMenu();

    public Formatka() {
        this.add(new JLabel("Right-click for popup menu."));
        menuPopup.add(klienciMenuItem);
        this.setComponentPopupMenu(menuPopup);
    }

    private void display() {
        JFrame f = new JFrame("Formatka");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(this);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Formatka().display();
            }
        });
    }
}
like image 92
trashgod Avatar answered Jan 07 '23 17:01

trashgod