Click to See Complete Forum and Search --> : JPopupMenu: How to use?


Valerie Bradley
August 24th, 1999, 04:13 PM
To all,

I am trying to implement my first popup menu using JPopupMenu. I'm using Java 1.2 (a.k.a Java 2) with Swing components.

I know that I need to make a JPopupMenu object, that it is populated with JMenuItem objects, and that I need to implement the PopupMenuListener interface. However, I cannot get anything to work properly.

If someone out there can give me some sample code showing me how to make a simple pop-up menu, I'd appreciate it.

BTW, I am able to catch right-click mouse button presses, I'm just having difficulties making the menu appear.

Thanks!!

- Valerie
Software Engineer
Intel Corporation

* All opinions are mine and not those of my employer.

meherss
September 8th, 1999, 09:36 AM
Hey this is a set of code that I took out of my stuff that I am working on. This is not a full example but it focuses on what you need to do.


static private JPopupMenu m_popMenu;


// This was implemented on a JList and m_resList is the instance of JList.
class ClickListener extends MouseAdapter
{
public void mouseClicked(MouseEvent e)
{
if (e.isPopupTrigger())
m_popMenu.show(m_resList, e.getX(), e.getY());
else
{
m_nListSelection = m_resList.locationToIndex(e.getPoint());
}
}
public void mousePressed(MouseEvent e)
{
if (e.isPopupTrigger())
m_popMenu.show(m_resList, e.getX(), e.getY());
}
public void mouseReleased(MouseEvent e)
{
if (e.isPopupTrigger())
m_popMenu.show(m_resList, e.getX(), e.getY());
}
}

private void buildPopUp()
{
m_popMenu = new JPopupMenu();
JMenuItem menuItem = new JMenuItem("Delete" );
menuItem.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
//removeFromList();
}
});
m_popMenu.add( menuItem ) ;
}





Hope this will help you. If not pl. mail your
code I 'll go thru it.

Annu Ittyachen
October 25th, 1999, 02:38 AM
Step 1:- Create your popup menu

//create the JPopUpMenu
popup = new JPopupMenu();
//add the menu item to the popup menu
menu1 = new JMenuItem("Menu 1");
menu1.setEnabled(false);
menu1.addActionListener(this);
popup.add(menu1);
//add a separator
popup.addSeparator();
//add the "Pass" menu item to the popup menu
menu2 = new JMenuItem("Menu 2");
menu2.setEnabled(false);
menu2.addActionListener(this);
popup.add(menu2);

Step2:- In the place where you catch your right click bring up your popup menu
//Bring up the context menus
popup.show(e.getComponent(),e.getX(), e.getY());

Step 3:- Catch the menu clicked in the ActionPerformed event
JMenuItem menuClicked = (JMenuItem)e.getSource();
if(menuClicked.equals(menu1))
------;
else if(menuClicked.equals(menu2))
------;