Adding JPopupMenu to JPanel

My code is:

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 press the right mouse button. What for?

+4
source share
3 answers

Works for me when adding to 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(); } }); } } 
+8
source

You did not set the layout, so the component is probably not added to the JFrame. Set the layout in the JFrame using setLayout(new BorderLayout()); .

+2
source

This works with JFrame: D

  import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JFrame; public class Popup extends JFrame{ JMenuItem item1,item2; static JPopupMenu pop; Popup(){ item1= new JMenuItem("This is Menu Item"); item2= new JMenuItem("This is another Menu Item"); pop= new JPopupMenu(); MouseListener popListener = new PopupListener(); pop.add(item1); pop.add(item2); addMouseListener(popListener); setLocationRelativeTo(null); pack(); setVisible(true); } public static void main(String a []){ new Popup(); } } class PopupListener extends MouseAdapter{ public void mousePressed(MouseEvent e) { maybeShowPopup(e); } public void mouseReleased(MouseEvent e) { maybeShowPopup(e); } private void maybeShowPopup(MouseEvent e) { if (e.isPopupTrigger()) { Popup.pop.show(e.getComponent(), e.getX(), e.getY()); } } } 
+1
source

Source: https://habr.com/ru/post/1414726/


All Articles