Java AWT PopupMenu
Last Updated :
13 Nov, 2023
In Java, AWT (Abstract Window Toolkit) provides a PopupMenu course that allows you to make pop-up menus in your graphical user port (GUI) applications. A PopupMenu is a setting menu that appears when you right-click on a component, such as a button or a venire. It provides a set of options or actions that the user can select from. In this clause, we testament explore the syntax, methods, and constructors of the Java AWT PopupMenu.
Syntax of Class Declaration
The class declaration for PopupMenu in Java AWT is as follows:
public class PopupMenu extends Menu
Here, PopupMenu is a subclass of the Menu class. It inherits properties and methods from the Menu class and adds functionality specific to pop-up menus.
Methods for PopupMenu
List of all methods used in the PopupMenu application with description
Adds the specified MenuItem to this PopupMenu.
|
Displays the pop-up menu at the specified location (x, y) relative to the given component (origin).
|
Removes the MenuItem at the specified index from the PopupMenu.
|
Removes the specified MenuItem from the PopupMenu.
|
Removes all the items from the PopupMenu.
|
Constructors
The PopupMenu class has a default constructor that can be used to create a PopupMenu:
PopupMenu popupMenu = new PopupMenu();
Example of Java AWT PopupMenu
Below is the implementation of Java AWT PopupMenu:
Java
import java.awt.*;
import java.awt.event.*;
public class PopupMenuExample {
public static void main(String[] args) {
Frame frame = new Frame( "GeeksforGeeks PopupMenu Example" );
frame.setSize( 400 , 400 );
PopupMenu popupMenu = new PopupMenu();
MenuItem menuItem1 = new MenuItem( "Option 1" );
MenuItem menuItem2 = new MenuItem( "Option 2" );
MenuItem menuItem3 = new MenuItem( "Option 3" );
popupMenu.add(menuItem1);
popupMenu.add(menuItem2);
popupMenu.add(menuItem3);
frame.add(popupMenu);
frame.addMouseListener( new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
popupMenu.show(frame, e.getX(), e.getY());
}
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
popupMenu.show(frame, e.getX(), e.getY());
}
}
});
frame.setLayout( null );
frame.setVisible( true );
}
}
|
Output:
Output Window:
Conclusion
The Java AWT PopupMenu family is a utile factor for creating context menus in your GUI applications. It provides a way to represent options or actions to the user in a pop-up form. By knowing its syntax, methods, and constructors, you can enhance the interactivity of your Java applications.
Share your thoughts in the comments
Please Login to comment...