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:


















PROGRAM
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
  mGreen.addActionListener(this);
  mCyan.addActionListener(this);
  mMagenta.addActionListener(this);
  
  // Adding menu items to popup menu
  popupMenu.add(mGreen);
  popupMenu.add(mCyan);
  popupMenu.add(mMagenta);
  
  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) {
     popupMenu.show(PopupMenuDemo.this, me.getX(), me.getY());
    }
   }
  });
  
  // Handling window event
  addWindowListener(new WindowAdapter() {
   
   public void windowClosing(WindowEvent we) {
    dispose();
   }
  });
 }
 
 public void actionPerformed(ActionEvent ae) {
  
  if(ae.getSource() == mGreen) 
   setBackground(Color.GREEN);
  else if(ae.getSource() == mCyan)
   setBackground(Color.CYAN);
  else
   setBackground(Color.MAGENTA);
 }
 
 public static void main(String args[]) {
  
  PopupMenuDemo p = new PopupMenuDemo();
  p.setTitle("Program for popup menu");
  p.setSize(400, 400);
  p.setVisible(true);
 }
}


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 input age from user and throw user-defined exception if entered age is negative