How to use AWT JPopupMenu and AWT choice bar in Java

In this program, we will learn about the two important predefined classes. Which provides the many methods for creating an attractive and easy swing program. These classes are-:

  • AWT Choice
  • AWT PopupMenu

With the AWT Choice class, we can create a Choice bar with many options available for the selection.

With the AWTPopup Menu class, we can create a Popup menu. This type of menu is a free poised menu.

Java Program: AWT Choice Bar

import java.awt.*;  
public class ChoiceExample  
{  
        ChoiceExample(){  
        Frame f= new Frame();  
        Choice c=new Choice();  
        c.setBounds(100,100, 75,75);  
        c.add("Item 1");  
        c.add("Item 2");  
        c.add("Item 3");  
        c.add("Item 4");  
        c.add("Item 5");  
        f.add(c);  
        f.setSize(400,400);  
        f.setLayout(null);  
        f.setVisible(true);  
     }  
public static void main(String args[])  
{  
   new ChoiceExample();  
}  
}

In this program, we will be simply declaring the object of Choice class and add on the frame.




The output of the program

AWT choice bar java program

AWT Choice Bar Java Program

Java Program of JPopupMenu (Popup in Java)

import java.awt.*;  
import java.awt.event.*;  
class PopupMenuExample  
{  
     PopupMenuExample(){  
         final Frame f= new Frame("PopupMenu Example");  
         final PopupMenu popupmenu = new PopupMenu("Edit");   
         MenuItem cut = new MenuItem("Cut");  
         cut.setActionCommand("Cut");  
         MenuItem copy = new MenuItem("Copy");  
         copy.setActionCommand("Copy");  
         MenuItem paste = new MenuItem("Paste");  
         paste.setActionCommand("Paste");      
         popupmenu.add(cut);  
         popupmenu.add(copy);  
         popupmenu.add(paste);        
         f.addMouseListener(new MouseAdapter() {  
            public void mouseClicked(MouseEvent e) {              
                popupmenu.show(f , e.getX(), e.getY());  
            }                 
         });  
         f.add(popupmenu);   
         f.setSize(400,400);  
         f.setLayout(null);  
         f.setVisible(true);  
     }  
public static void main(String args[])  
{  
        new PopupMenuExample();  
}  
}  

In this program, we will be using the JPopupMenu class for creating the object of the popup menu. First, we create a frame and set the size after that we create an object of JPopUPMenu class and set the size. After that, we add the menu item by using the JMenuItem class.

The output of the program

JPopupMenu Java AWT Program

Java popup menu output

You may also learn,


Leave a Reply

Your email address will not be published. Required fields are marked *