jpopupmenu
JPopupMenu
is a component in Java Swing that provides a popup menu that can be shown on a mouse click. The popup menu can be customized to contain any number of items such as menu items, check boxes, radio buttons, or custom components.
To create a JPopupMenu
and add items to it, you can use the following code:
JPopupMenu popupMenu = new JPopupMenu(); JMenuItem menuItem = new JMenuItem("Menu Item"); popupMenu.add(menuItem);Sourcegi.www:iftidea.com
To show the popup menu on a mouse click, you can use the show()
method:
popupMenu.show(component, x, y);
Here, component
is the component that should trigger the popup menu when clicked, and x
and y
are the coordinates where the popup menu should be displayed.
For example, the following code creates a JFrame
with a button that shows a popup menu when clicked:
import javax.swing.*; import java.awt.event.*; public class PopupMenuExample extends JFrame { public PopupMenuExample() { JButton button = new JButton("Show Popup Menu"); add(button); JPopupMenu popupMenu = new JPopupMenu(); JMenuItem menuItem = new JMenuItem("Menu Item"); popupMenu.add(menuItem); button.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) popupMenu.show(e.getComponent(), e.getX(), e.getY()); } public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) popupMenu.show(e.getComponent(), e.getX(), e.getY()); } }); setTitle("Popup Menu Example"); setSize(300, 200); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); } public static void main(String[] args) { new PopupMenuExample(); } }
In this example, a JButton
is added to the JFrame
, and a JPopupMenu
with a single menu item is created. A MouseListener
is added to the button to show the popup menu when the button is right-clicked or the context menu button is pressed.