A Tiny JPopupMenu Example - Swing

Here is a tiny example illustrating JPopupMenu on JButton in Swing.
import javax.swing.*;
import java.awt.*;
class JPopupMenuExample extends JFrame
{
JButton b;
JPopupMenu p;
JMenuItem m1,m2,m3,m4;

    public JPopupMenuExample()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("JPopupMenu Example");
        setLayout(new FlowLayout());
        setDefaultCloseOperation(EXIT_ON_CLOSE);
       
        b=new JButton("Right click me");
        add(b);
       
        p=new JPopupMenu();
        m1=new JMenuItem("Item 1");
        m2=new JMenuItem("Item 2");
        m3=new JMenuItem("Item 3");
        m4=new JMenuItem("Item 4");
       
        b.setComponentPopupMenu(p);
       
        p.add(m1);
        p.add(m2);
        p.add(m3);
        p.add(m4);
       
       
        setSize(400,400);
        setVisible(true);
    }
   
    public static void main(String args[])
    {
        new JPopupMenuExample();
    }
}
setComponentPopupMenu(): This method is present in the JComponent class, so inherited to all light-weight swing components. This method takes JPopupMenu object. Using the add() we can add JMenuItems to the popup menu.
I would be grateful, if you share this post.

“Simplicity is the ultimate sophistication.” - Leonardo da Vinci

No comments: