Share on Google+Share on Google+

Pop-up Menus

A PopupMenu is similar to a Menu as it contains MenuItem objects.

Pop-up Menus


A PopupMenu is similar to a Menu as it contains MenuItem objects. The Pop-up Menu can be popped over any component while generating the appropriate mouse event rather than letting it appear at the top of a Frame. Menu class can only be added to a Frame and not to the Applet. To add it to the Applet you need to use the Swing component set. 

In the program code given below, we have used MouseEvent.isPopupTrigger() method to trigger the MouseEvent that pops up the menu. The example below shows the triggering of a pop-up menu and its activation through a command button.


import java.awt.*; 
import java.awt.event.*; 
import java.applet.Applet;

public class PopupMenuDemo extends Applet
  Button b; 
  TextField msg; 
  PopupAppMenu m; 
  public PopupMenuDemo(){ 
  b = new Button("Pop-up Menu")
  add(b, BorderLayout.NORTH)
  msg = new TextField()
  add(msg, BorderLayout.SOUTH)
  m = new PopupAppMenu(this)
  b.addActionListener(new ActionListener(){ 
  public void actionPerformed(ActionEvent e){, 2020)
  addMouseListener(new MouseAdapter(){ 
  public void mousePressed(MouseEvent e){ 
  if (e.isPopupTrigger()), e.getX(), e.getY())
  public void mouseReleased(MouseEvent e){ 
  if (e.isPopupTrigger()), e.getX(), e.getY())
  public static void main(String[] args){ 
  PopupMenuDemo app = new PopupMenuDemo()
  class PopupAppMenu extends PopupMenu 
  implements ActionListener
  PopupMenuDemo ref; 
  public PopupAppMenu(PopupMenuDemo ref){ 
  this.ref = ref; 
  MenuItem mi; 
  add(mi = new MenuItem("Copy"))
  add(mi = new MenuItem("Open"))
  add(mi = new MenuItem("Cut"))
  add(mi = new MenuItem("Paste"))
  public void actionPerformed(ActionEvent e){ 
  String item = e.getActionCommand()
  ref.msg.setText("Option Selected: " + item)

Output of the program:


C:\newprgrm>appletviewer PopupMenuDemo.html

Download this example.




Posted on: December 18, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: Pop-up Menus   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image