Friday, June 19, 2009

How to create pop-up menus in Java

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:-

1.Create an object of the JPopupMenu class.
2.Create object of the Menu class for each menu you want to add on the menu bar.
3.Call the add() method of the JPopupMenu class to add each menu object to the pop-up menu.
4.Create objects of the JMenuItem or CheckboxMenuItem class for each item that you want to in the menu.
5.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( );
}
}

Useful Links:-
Home
Menus
MenuBars

0 comments:

About This Blog

This Blog is all about Java and programming.This blog is written by Vaibhav Pandey(Read More about him) .He is a Computer Science Graduate .You can contact the author at javatute@gmail.com for any suggestion or Query.You can also contact the author for advertising on this blog.All the material presented here is the property of author and its reproduction in any form is strictly prohibited.

Disclaimer:-Download links provided here are not of author in any means.These are found over the Internet.
Page copy protected against web site content infringement by Copyscape

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Back to TOP