Show Popup menu on JButton Click

Have you ever wondered, showing a popup menu when a button is clicked? Quite similar to the concept of menu buttons as created earlier, this is another approach that uses JButton to do the job. The aim of the program below is to show a popup menu when an action is performed on JButton. This is quite simple, if you can understand the 2 important lines of code. The following program contains the code you need to do the job, most of which it is what you can easily decipher. I always write commentaries, to let you grasp better.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MenuButton2 extends JFrame
JButton jb,jb1;
JPopupMenu menu;
JMenuItem m1,m2,m3,m4;

    public MenuButton2()
    private void createAndShowGUI()
        // Set frame properties
        setTitle("Menu Button");
        setLayout(new GridBagLayout());
        // Create JButtons
        jb=new JButton("Button");
        jb1=new JButton("Click me");
        // Create a JPopupMenu
        menu=new JPopupMenu();
        // Create JMenuItems
        m1=new JMenuItem("Item 1");
        m2=new JMenuItem("Item 2");
        m3=new JMenuItem("Item 3");
        m4=new JMenuItem("Item 4");
        // Add JMenuItems to JPopupMenu
        // Create an ActionListener which
        // will be used by two buttons (in common)
        ActionListener a1=new ActionListener(){
            public void actionPerformed(ActionEvent ae)
                // Call the showPopup method
                // This takes ActionEvent to get
                // the event source
        // Add ActionListener to JButtons
        // Add the JButtons
        // Set some size and show
    // This method does it all!
    private void showPopup(ActionEvent ae)
        // Get the event source
        Component b=(Component)ae.getSource();
        // Get the location of the point 'on the screen'
        Point p=b.getLocationOnScreen();
        // Show the JPopupMenu via program
        // Parameter desc
        // ----------------
        // this - represents current frame
        // 0,0 is the co ordinate where the popup
        // is shown,0,0);
        // Now set the location of the JPopupMenu
        // This location is relative to the screen
    public static void main(String args[])
        new MenuButton2();
If you have a better way, I would like to hear it from you, please feel free to drop a comment for anything that you want to.

Posted by at on

Tags: Swing Hacks,