PopUp Menus
Pop-up menus are the menus that are displayed when a user clicks the right mouse button.They are sometimes also known as short-cut menus.
Short cut menus are very handy in cases where some functionality you want to provide like adding a help menu to all controls on right click.
Step for creating Pop-up menus:
- Create an object of the JPopupMenu class.
- Create object of the Menu class for each menu you want to add on the menu bar.
- Call the add() method of the JPopupMenu class to add each menu object to the pop-up menu.
- Create objects of the JMenuItem or CheckboxMenuItem class for each item that you want to in the menu.
- Call the add() method of the Menu class to add each item to its appropriate menu.
Example Source code:
//PopUpColorMenu.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PopUpColorMenu
{
Component selectedComponent;
public PopUpColorMenu( ) {
JFrame frame = new JFrame("PopUpColorMenu v1.0");
final JPopupMenu colorMenu = new JPopupMenu("Color");
colorMenu.add(makeMenuItem("Red"));
colorMenu.add(makeMenuItem("Green"));
colorMenu.add(makeMenuItem("Blue"));
MouseListener mouseListener = new MouseAdapter( ) {
public void mousePressed(MouseEvent e) { checkPopup(e); }
public void mouseClicked(MouseEvent e) { checkPopup(e); }
public void mouseReleased(MouseEvent e) { checkPopup(e); }
private void checkPopup(MouseEvent e) {
if (e.isPopupTrigger( )) {
selectedComponent = e.getComponent( );
colorMenu.show(e.getComponent(), e.getX( ), e.getY( ));
}
}
};
frame.getContentPane( ).addMouseListener(mouseListener);
frame.setSize(200,50);
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setVisible(true);
}
private JMenuItem makeMenuItem(String label) {
JMenuItem item = new JMenuItem(label);
return item;
}
public static void main(String[] args) {
new PopUpColorMenu( );
}
}