Program to create a Popup Menu using Java AWT

This tutorial shows you how to create a simple popup menu in Java. Popup menu is a menu which appears when you right click on mouse. For example, to copy, paste something in computer you right click and it will show the popup menu like:

Here you have to create a popup menu with basic three options Green, Cyan and Magenta. After selecting particular option it will change the background color of window. The output of the same is given below.

BEFORE selecting option from popup menu :

AFTER selecting option Magenta output will be:

import java.awt.*;
import java.awt.event.*;

class PopupMenuDemo extends Frame implements ActionListener {

 PopupMenu popupMenu;
 MenuItem mGreen, mCyan, mMagenta;
 public PopupMenuDemo() {
  // Creating PopupMenu
  popupMenu = new PopupMenu();
  // Creating popup menu items
  mGreen = new MenuItem("Green");
  mCyan = new MenuItem("Cyan");
  mMagenta = new MenuItem("Magenta");
  // Adding action listeners to menu items
  // Adding menu items to popup menu
  add(popupMenu); // Add popup menu to Frame window
  // Handling mouse event
  addMouseListener(new MouseAdapter() {
   public void mousePressed(MouseEvent me) { // Checking for Mouse right click
    if(me.getButton() == MouseEvent.BUTTON3) {, me.getX(), me.getY());
  // Handling window event
  addWindowListener(new WindowAdapter() {
   public void windowClosing(WindowEvent we) {
 public void actionPerformed(ActionEvent ae) {
  if(ae.getSource() == mGreen) 
  else if(ae.getSource() == mCyan)
 public static void main(String args[]) {
  PopupMenuDemo p = new PopupMenuDemo();
  p.setTitle("Program for popup menu");
  p.setSize(400, 400);


Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to draw Smiley in Applet