MouseEvents on JPopupMenu and JMenuItem

Hi
I am trying to get the mouse events from JPopupMenu
and JMenuItem , but nothing happens
I display the popup once a button is pressed , the popup is displayed but once I click it there is no response
can some one help
I am attaching the code
import javax.swing.*;
import java.awt.event.*;
public class Pop extends JFrame implements ActionListener{
     JPopupMenu popup = new JPopupMenu();
     JMenuItem item = new JMenuItem("one");
     JMenuItem item2 = new JMenuItem("two");
     JButton ok = new JButton("ok");
     Pop(){
          H hand = new H();
          popup.add(item);
          popup.add(item2);
          popup.addMouseListener(hand);
          item.addMouseListener(hand);
          item2.addMouseListener(hand);
          ok.addActionListener(this);
          getContentPane().add(ok);
          setSize(300,300);
          show();
     public void actionPerformed(ActionEvent ee){
          popup.show(ok , 5,5);
     public static void main(String[] args){
          new Pop();
     class H extends MouseAdapter{
          public void mouseClicked (MouseEvent e){
               JOptionPane.showMessageDialog(null,e.toString());
}

If you are just trying to get something done when a menuitem is clicked, then you can try to use actionListener instead of the mouselistener. Try the following:
ActionListener al = new ActionListener()
public void actionPerformed()
OptionPane.showMessageDialog(null,e.toString());
item.addActionListener(al);
item2.addActionListener(al2);
Now when you click an item, the dialog box would be shown.

Similar Messages

  • How can I distinguish a JMenuItem , JPopupMenu and TopLevelMenu?

    I used the following methods to get the component who (a menu)gains the focus:
    JComponent com = JFrmame.getFocusOwner();
    or
    MenuSelectionManager menuMgr = MenuSelectionManager.defaultManager();
    MenuElement[] menuPath = menuMgr.getSelectedPath();
    if(menuPath != 0) {
    JComponent comp = Array.get(menuPath, menuPath.length-1); // this is the item with the focus
    then I need to use getAction() to get the menuItem's action. But how can I filter JMenuItem and JPopUpMenu from TopLevelMenu (JMenuBar item) ?
    Thanks!

    The instanceof may provide the simplest solution, since JPopupMenu, JMenuBar and JMenuItem don't have any kind of ancestor relationship with each other.if (comp instanceof JPopupMenu) {
        // Popup
    } else if (comp instanceof JMenuItem) {
        // Item
    } else if (comp instanceof JMenuBar) {
        // Bar
    } else ...?Hope this helps,
    -Troy

  • JMenu and JMenuItem - Images

    How to put an image in front of the JMenu text?
    JMenuItem has a constructor to insert the icon.
    Is their a reason why it not in the JMenu constructors?
    Sometimes I just want to put a 16 pixel gap in front of the JMenuItem or JMenu if it has no Image. Can one do that without inserting a blank
    Image?
    Thanks

    Have you tried just setting it via setIcon()? Since both JMenu and
    JMenuItem inherit from AbstractButton, this may work; I say may
    since more than likely it is up to the L&F UI to do the right thing.
    A quick browse shows that it ought to work for at least the basic
    L&Fs though.
    As far as the empty gap, looks like you might be out of luck by
    default, but this too is up to the L&F. For instance, some look and
    feels line up the text properly if an item doesn't have an icon.
    As a quick fix, though, you could probably just set the icon to
    something like
    menuItem.setIcon( new Icon() {
        public int getIconWidth() { return 16; }
        public int getIconHeight() { return 0; }
        public void paintIcon(Component c, Graphics g, int x, int y) {}
    });: jay

  • JPopupMenu - setSelected (JMenuItem)

    Hi
    I have a popup menu with a number of menu items which I add to the popupMenu. I call setSelected with one of them (not the first added) and then show. But it is always the first item that is shown as being selected, even though when I call getSelectionModel().getSelectedIndex it returns the index of the item I set to be selected.
    I can see that others have had similar problems, but haven't been able to find anyone that could answer them.

    Why do you want the menu item selected?
    This works, but may not fully answer your question. ***************************************************************************************************
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.BorderLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JMenuItem;
    import javax.swing.JPopupMenu;
    import javax.swing.UIManager;
    public class PopupTest extends JFrame implements ActionListener
    public static void main( String[] args )
    PopupTest test = new PopupTest();
    test.pack();
    test.show();
    private JPopupMenu popup;
    private JMenuItem menuItem1;
    private JMenuItem menuItem2;
    public PopupTest()
    try
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    catch( Exception e )
    popup = new JPopupMenu();
    menuItem1 = new JMenuItem( "Item 1");
    menuItem1.setActionCommand( "Item 1");
    menuItem1.addActionListener( this );
    menuItem2 = new JMenuItem( "Item 2");
    menuItem2.setActionCommand( "Item 2");
    menuItem2.addActionListener( this );
    popup.add( menuItem1 );
    popup.add( menuItem2 );
    JButton button = new JButton("Button 1");
    button.setActionCommand("Button 1");
    button.addActionListener( this );
    this.getContentPane().add( button );
    button = new JButton("Button 2");
    button.setActionCommand("Button 2");
    button.addActionListener( this );
    this.getContentPane().add( button, BorderLayout.EAST );
    public void actionPerformed(ActionEvent e)
              System.out.println(e.getActionCommand());
    popup.show( this, 0,0 );
    if( e.getActionCommand().equals( "Button 1" ) )
    popup.setSelected( menuItem1 );
    menuItem1.setArmed( true );
    menuItem2.setArmed( false );
    else if( e.getActionCommand().equals( "Button 2" ) )
    popup.setSelected( menuItem2 );
    menuItem1.setArmed( false );
    menuItem2.setArmed( true );

  • Problem with JPopupMenu and JTree

    Hi,
    Is there any way to have different JPopupMenu for every node.
    When I right click on the treenode there is popup menu have a "*JCheckBoxMenuItem*". By default the value of that checkbox is false. Now when i try to right click on a particular node and select the checkbox the selected value gets applied to rest of all nodes also.
    How can i just set the value of the checkbox to one perticular node.
    my code is
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class TreePopupMenuTest {
      public JComponent makeUI() {
        JTree tree = new JTree();
        tree.setComponentPopupMenu(new TreePopupMenu());
        JPanel p = new JPanel(new BorderLayout());
        p.add(new JScrollPane(tree));
        p.setPreferredSize(new Dimension(320, 240));
        return p;
      class TreePopupMenu extends JPopupMenu {
        private TreePath path;
        private JCheckBoxMenuItem compress=new JCheckBoxMenuItem("Compress");
        public TreePopupMenu() {
          super();
          add(compress);
          compress.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent ie) {
                            if(compress.getState()){
                                 compress.setState(true);
                                    System.out.println("compress clicked");
                            else{
                                 compress.setState(false);
                                    System.out.println("uncompress");
        public void show(Component c, int x, int y) {
          JTree tree = (JTree)c;
          path = tree.getPathForLocation(x, y);
          if(path!=null && path==tree.getAnchorSelectionPath()) {
            super.show(c, x, y);
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          public void run() { createAndShowGUI(); }
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new TreePopupMenuTest().makeUI());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }Please help me as soon as possible.
    Thanks.
    Edited by: Kavita_S on Apr 23, 2009 11:49 PM

    Hi,
    Do you know this link?
    [How to Use Trees|http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html]
    Please help me as soon as possible.Sorry that I'm not good at English, I don't understand what you mean.
    Anyway, here's a quick example:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class TreePopupMenuTest3 {
      public JComponent makeUI() {
        JTree tree = new JTree();
        tree.setComponentPopupMenu(new TreePopupMenu());
        JPanel p = new JPanel(new BorderLayout());
        p.add(new JScrollPane(tree));
        p.setPreferredSize(new Dimension(320, 240));
        return p;
      class TreePopupMenu extends JPopupMenu {
        private TreePath path;
        private JCheckBoxMenuItem compress = new JCheckBoxMenuItem("Compress");
        public TreePopupMenu() {
          super();
          add(compress);
          compress.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ie) {
              if (compress.getState()) {
                System.out.println("compress clicked");
                setSelectedPath(path, true);
              } else {
                System.out.println("uncompress");
                setSelectedPath(path, false);
        public void show(Component c, int x, int y) {
          JTree tree = (JTree)c;
          path = tree.getPathForLocation(x, y);
          if (path!=null && path==tree.getAnchorSelectionPath()) {
            compress.setState(isSelectedPath(path));
            super.show(c, x, y);
      class MyData {
        public boolean flag;
        public String name;
        public MyData(String name, boolean flag) {
          this.name = name;
          this.flag = flag;
        @Override public String toString() {
          return name;
      //private Set<TreePath> selectedPath = new HashSet<TreePath>();
      private void setSelectedPath(TreePath p, boolean flag) {
        //if (flag) selectedPath.add(p);
        //else    selectedPath.remove(p);
        DefaultMutableTreeNode node =
              (DefaultMutableTreeNode)p.getLastPathComponent();
        Object o = node.getUserObject();
        if (o instanceof MyData) {
          ((MyData)o).flag = flag;
        } else {
          node.setUserObject(new MyData(o.toString(), flag));
      private boolean isSelectedPath(TreePath p) {
        //return selectedPath.contains(p);
        Object o =
              ((DefaultMutableTreeNode)p.getLastPathComponent()).getUserObject();
        return (o instanceof MyData)?((MyData)o).flag:false;
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          public void run() {
            createAndShowGUI();
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new TreePopupMenuTest3().makeUI());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

  • JWindow, JPopupMenu and flicker.

    I've trawled through earlier posts to these forums and found problems which, from their description, appear similar, but I haven't been able to find any answers that work for me. I would be very grateful for any assistance.
    I have a JWindow sized to fill the entire screen. This JWindow contains a subclass of JPanel which draws a diagram. The user clicks on elements of the diagram and pops up a JPopupMenu to select actions. JPopupMenu.show() is called with the JPanel as the invoker argument and x and y coords calculated so that it is always contained within the JPanel. As the JPopupMenu is shown and hidden there is a very noticable flicker.
    However, when the JPanel is contained in a JFrame there is no flicker.
    At first I thought this was a double buffering problem, but this doesn't seem to be the case.
    Any thoughts?
    Thanks.

    Try to call the JPopupMenu on a new Thread.
    Noah

  • JMenus and JMenuItems

    i have a JMenu called jMenu2, in its action performed method i would like it to add to the bottom of its list a new JMenuItem while the program is running.
    private void jMenu2ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
           jMenu2.add("hi");
    }so why can i not see this new menu item? i have tried many refreshing methods from JMenu with no luck

    I wouldn't expect it to show up immediately if it's being added as a result of clicking another item on the same JMenu, only next time you pull that JMenu down. If that doesn't happen, I would try creating a new JMenuItem("hi"), call setVisible(true) on it, and then add it to the JMenu. You shouldn't need to revalidate or repaint anything.

  • JMenu and JMenuItem

    Is it possible to have a JMenuItem within a JMenuItem? For example: Menu would drop down to a JMenuItem with two choices and when you click on one of the two choices another JMenuItem would have more choices available?

    Read this section from the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html]How to Use Menus for an example.

  • InternalFrameListener and JMenuItem problem

    Hi there, I did the following (just an outline, I know, that program is not working.... :))
    class A{
    static JMenuItem m_saveMenu;
    A(){
    JMenuBar mB = new JMenuBar();
    m_saveMenu = new JMenuItem("Save As...");
    class B{
    JInternalFrame iFrame = new JInternalFrame();
    iFrame.addInternalFrameListener(new MyListener());
    class MyListener extends InternalFrameAdapter{
         public void internalFrameActivated (InternalFrameEvent e){
              A.m_saveMenu.setEnabled(true);     }
         public void internalFrameDeactivated(InternalFrameEvent e){
    A.m_saveMenu.setEnabled(false);
    So if I (in my working program) create a new JInternalFrame and activate it I get the following error message:
    Exception occurred during event dispatching:
    java.lang.NullPointerException
    why could that be??
    Thx
    Charly

    hi,
    I mean this is obvious: You didn't initialize the menu item, you just declared it! And the listener might be used before the constructor of class A is called.
    You could do the following now:
    static JMenuItem m_saveMenu=new JMenuItem("Save As...");
    unless you are sure that the constructor of class A and with it the initialization of the menu item goes ahead.
    best regards, Michael

  • JMenuBar and JMenuItem

    I need to have a JMenuItem in a JMenuBar but I'm having difficulties. If I have a JMenu with no children JMenuItems below it and I add that JMenu to the JMenuBar, I get a small square below the JMenu when I click it. I tried to add a JMenuItem to the JMenuBar in place of the childless JMenu but when I do that, the JMenuItem spans the width of the JMenuBar and that isn't good. Is there a way to have a JMenuItem as a part of a JMenuBar without the adverse effects described just now? Thanks, Jeremy

    I used gridBagLayout to do it as follows
    ivjTestFrameJMenuBar = new javax.swing.JMenuBar();
                   ivjTestFrameJMenuBar.setLayout(new GridBagLayout());
                   ivjTestFrameJMenuBar.setName("TestFrameJMenuBar");
                   java.awt.GridBagConstraints constraintsJMenu1 = new java.awt.GridBagConstraints();
                   constraintsJMenu1.gridx = 0; constraintsJMenu1.gridy = 0;
                   constraintsJMenu1.insets = new java.awt.Insets(4, 4, 4, 4);
                   ivjTestFrameJMenuBar.add(getJMenu1(), constraintsJMenu1);
                   java.awt.GridBagConstraints constraintsJMenuItem = new java.awt.GridBagConstraints();
                   constraintsJMenuItem.gridx = 1; constraintsJMenuItem.gridy = 0;
                   constraintsJMenuItem.insets = new java.awt.Insets(4, 4, 4, 4);
                   ivjTestFrameJMenuBar.add(new javax.swing.JMenuItem("Item 1"), constraintsJMenuItem);
                   java.awt.GridBagConstraints constraintsJMenu2 = new java.awt.GridBagConstraints();
                   constraintsJMenu2.gridx = 2; constraintsJMenu2.gridy = 0;
                   constraintsJMenu2.anchor = java.awt.GridBagConstraints.WEST;
                   constraintsJMenu2.weightx = 1.0;
                   constraintsJMenu2.insets = new java.awt.Insets(4, 4, 4, 4);
                   ivjTestFrameJMenuBar.add(getJMenu2(), constraintsJMenu2);see how it works for you, it seemed to work ok for me
    Sok

  • JMenu and JMenuItems

    hi
    does anybody know how i can disable menuitems
    and enable them on some given events?
    would help me very much!
    thanx

    A good way to do this is to use Actions - define an Action object for each menu item (including text and an icon if you want), then just add the actions to the menu, and it will show them with icons automatically.
    Then if you do setEnabled(false) on the action, the menu item is greyed out. Also, you can add these Actions to other components such as a JToolBar, which would automatically render them as buttons (these also get greyed out when disabed).
    The big benefit is that all your "action" code is in one place, so the menu and the toolbar both call the same code.
    For a tutorial, see
    http://java.sun.com/docs/books/tutorial/uiswing/misc/action.html

  • Custom text for JMenu and JMenuItem

    hey guys
    right now i can do a :
    JMenu menu = new JMenu("File");but how can i customize the text on the Menu a.k.a "file" so may be it looks bigger or a different color ?
    ive looked at the API i can see that JMenu takes "Action" object too which describes the look. I know Action is an interface and i havent been able to find a suitable class that implements this interface
    so how should i go about changing the text look/feel ?
    thank in advance

    so may be it looks bigger or a different color ?Read the API. There are many different set??? methods which allow you to change the properties of the component including the font size and color of the text.
    i can see that JMenu takes "Action" object too which describes the look.The Action has nothing to do with the look (other then providing the text to display). It has to do with the Action that happens when you select the menu item.

  • Using JMenu and JMenuItem

    I have a JMenu attached to a JFrame, along with a panel and a graphic object which extends Canvas. When I click the Menu bar, the menu does not show, it actually falls behind the Canvas. I can see it if I remove the Canvas. How do you make it appear over the Canvas or the items drawn over the Canvas?
    Any help will be greatly appreciated.
    Pradeep Gupta
    [email protected]
    Mon 03Nov03 10:31

    You are mixing heavyweight and lightweight components. Can you subclass JComponent or JPanel instead of Canvas? That would solve your problem.

  • JAWS and JMenuItem - PLEASE HELP

    Hi,
    I try to access to disabled menu options with JAWS 6.0 but it can read this.
    How I can do that JAWS read de disabled menu options, same that appears on Windows Menus?
    Thanks,
    Mentu
    PS: Sorry for my bad english.

    Well, I modified the code I provided a little ... if you need it just ask ... and fixed all my keyboard problems. As for the mouse reading the wrong thing, I rewrote the mouseListener and set the accessibleName before the selection is made and it works. This is just crazy ... Sun needs to make their widgets more accessible in the next release. I am doing everything that sun specifically says not to do in order to make stuff accessible ... but what else can I do?

  • SystemTray and Swing question

    Not sure if this should go in AWT or here, but here goes.
    I have implemented system tray functionality in my program, and for all purposes, it works fine. However, it's a bit ugly, and doesn't have all the functionality I want it to have when the menu pops up. I'm using the stuff from java.awt, (TrayIcon, PopupMenu, and MenuItem) and as far as I can tell, these don't do much more than just give basic functionality. So I was wondering how to use Swing instead. Implementing the JPopupMenu and JMenuItems works fine, but I can't add a JPopupMenu to TrayIcon the same way as just PopupMenu.
    Basically, I just want to add icons to the menu items, and I can't figure out how to do it in java.awt. I should note that I suppose it is possible, as evidenced by the screenshots at this article:
    http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/systemtray/
    If anyone knows how to do that, or what, let me know.

    Well, I did some searching, and I'm not the only one confused about that screenshot. In any case, it looks like I'll have to use JDIC to do that.

Maybe you are looking for

  • Unable to sync calendar from iphone to itunes etc- message coming up

    Hi, Since I did an upgrade of itunes on my phone I keep getting this error when trying to sync with my phone and itunes "iTunes could not sync calendars to the iphone "iphone" because the sync server failed to sync the iPhone." Any advice on how I ca

  • MBA - Video display & resolution concerns

    Hello! My parents currently own an aging, first-generation white MacBook. I want to help them migrate to a newer laptop, possibly a MacBook Air aka MBA), within the next several months. I used to own a 15-inch MacBook Pro (2007 vintage, IIRC) but it

  • Insert row in a table control

    Hi, I have a requirement to insert a new row and delete an existing row from a table control. Please help me how to proceed with this. Thanks in advance. Suresh

  • Confirmation in status awaiting approval

    Hi I have activated WF10400010 but our confirmations ends up in "awaiting approval". I have done a consistency check and the wf and sub-wf are fine. But when I check in SWI1 I can see that tast WS10400011 is in status ERROR. When doing a test run of

  • Porta Content Development Technologies

    Hi, I want to know about different SAP Portal Content Development technologies available. Please refer me some help links where i can get all the info at one place. Thanks a lot. Kind regards, Ramesh.