Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

show PopupMenu in JMenuItem

843805Feb 6 2006 — edited Feb 6 2006
I want to show the popupmenu when users do the right click on the menuitem to do something like the mozilla or internet explorer Favorites menu which can be do right click to show the popup.
I tried this, but i always have the following problems:

1) I open the popupMenu with the popup.show( jmenuitem, mouseEvent.getX(), mouseEvent.getY())
I got the error : java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
:

2) Then, I do the menu stay show by overrided the doClick of the jmenuitem to do nothing. And show the popup with the same way. I got this error.
java.lang.NullPointerException
at javax.swing.plaf.basic.BasicPopupMenuUI$MouseGrabber.grabContainer(Unknown Source)

So, I try to do with the JMenu instead of the JMenuItem....

1.) when i open the popupMenu with
popup.show(jmenu,mouseEvent.getx(),mouseEvent.getY())

the popup is shown, but i can't access an Item in it. When I move the mouse over the popup then the jmenu will disappears ! And the popup never disappear!

2.) when i open the popupMenu with
popup.show(someComponent,mouseEvent.getx(),mouseEvent.getY())
the popup is shown, but the oldmenu disappears
in this case the items in the popup are accessible !

Below, this is the fragment of code.
=====================================================
//create popupmenu.
popupMenu = new JPopupMenu();
popupMenu.add( new JMenuItem("delete this link"));
popupMenu.add( new JMenuItem("go to this link"));

//create menubar.
JMenuBar menuBar = new JMenuBar();

//create favoritemenu.
JMenu favoriteMenu = new JMenu("Favorite");
JMenuItem link1 = new JMenuItem("http://java.sun.com");
link1.addMouseListener(new MouseAdapter(){

public void mouseReleased(MouseEvent e) {

if( e.isPopupTrigger() || SwingUtilities.isRightMouseButton(e) ){ //right-click

popupMenu.show(e.getComponent(), e.getX(), e.getY());

} else {
System.out.println( "left click=" + e.getSource() );
}
}
});

favoriteMenu.add( link1 );

menuBar.add( favoriteMenu );


thank's for help
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 6 2006
Added on Feb 6 2006
3 comments
161 views