This discussion is archived
12 Replies Latest reply: May 18, 2013 4:03 AM by ptoye RSS

Problem with mouse events and getModifiersEx

ptoye Newbie
Currently Being Moderated
This is more an API than a programming issue, but I can't find a suitable forum there.

I'm having a problem using getModifiersEx to find the state of the modifier keys when I click the mouse.

Several issues:

1) When I click the right button, the mouse event tells me that it's Button number 3, and when I release it, that the Meta key is down. If I have other modifiers keys pressed at the time, they are recognised and the Meta key isn't (!)

The button number is surprising (it's a 2-button plus wheel mouse) but not an issue. The key, however, is an issue.

2) The Alt-Gr key comes up as Ctrl-Alt, which definitely is an issue.

3) The modifiers keys aren't always recognised. This seems to happen if I move the mouse quickly before clicking.

Some annotated output follows. I can post the code (it uses Netbeans to generate it, so some tweaking may be needed) if it would help.



//left click
Button 1 pressed count=1
Button 1 released count=1
Button 1 clicked count=1

//Right-click
Button 3 pressed count=1
Button 3 released count=1 Meta
Button 3 clicked count=1 Meta

//alt-gr left click
Button 1 pressed count=1 Alt Ctrl
Button 1 released count=1 Alt Ctrl
Button 1 clicked count=1 Alt Ctrl

//Ctrl right click
Button 3 pressed count=1 Ctrl
Button 3 released count=1 Ctrl
Button 3 clicked count=1 Ctrl

//Right click again
Button 3 pressed count=1
Button 3 released count=1 Meta
Button 3 clicked count=1 Meta

//Shift right click
Button 3 pressed count=1
Button 3 released count=1 Shift
Button 3 clicked count=1 Shift

//alt right click
Button 3 pressed count=1 Alt
Button 3 released count=1 Alt
Button 3 clicked count=1 Alt

//shift right click
Button 1 pressed count=1 Shift

//quick movements
Button 1 pressed count=1
Button 1 released count=1 Ctrl

Button 1 pressed count=1
Button 1 released count=1 Ctrl
Button 1 clicked count=1 Ctrl

Button 1 pressed count=1
Button 1 released count=1 Alt
Button 1 clicked count=1 Alt
  • 1. Re: Problem with mouse events and getModifiersEx
    jtahlborn Expert
    Currently Being Moderated
    yes, code always helps.
  • 2. Re: Problem with mouse events and getModifiersEx
    ptoye Newbie
    Currently Being Moderated
    Well, you asked for it! It's pretty trivial. The output was a bit edited and the comments added by hand.

    It also thinks my mouse has 5 buttons; no idea where the other 2 are!
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package testmouseclick;
    
    import java.awt.event.MouseEvent;
    import java.awt.event.InputEvent;
    
    /**
     *
     * @author Peter
     */
    public class MouseCLick extends javax.swing.JFrame {
    
      /**
       * Creates new form MouseCLick
       */
      public MouseCLick() {
        initComponents();
        jTA1.setText("No of buttons: "+java.awt.MouseInfo.getNumberOfButtons()+"\n");
      }
    
      /**
       * This method is called from within the constructor to initialize the form.
       * WARNING: Do NOT modify this code. The content of this method is always
       * regenerated by the Form Editor.
       */
      @SuppressWarnings("unchecked")
      // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
      private void initComponents() {
    
        jScrollPane2 = new javax.swing.JScrollPane();
        jTA1 = new javax.swing.JTextArea();
    
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Test Mouse Click");
    
        jTA1.setColumns(20);
        jTA1.setRows(5);
        jTA1.addMouseListener(new java.awt.event.MouseAdapter() {
          public void mouseReleased(java.awt.event.MouseEvent evt) {
            jTA1MouseReleased(evt);
          }
          public void mouseClicked(java.awt.event.MouseEvent evt) {
            jTA1MouseClicked(evt);
          }
          public void mousePressed(java.awt.event.MouseEvent evt) {
            jTA1MousePressed(evt);
          }
        });
        jScrollPane2.setViewportView(jTA1);
    
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
          layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 390, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
          layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
        );
    
        pack();
      }// </editor-fold>                        
    
      private void jTA1MouseClicked(java.awt.event.MouseEvent evt) {                                  
        mouseAction(evt);
      }                                 
    
      private void jTA1MousePressed(java.awt.event.MouseEvent evt) {                                  
        mouseAction(evt);
      }                                 
    
      private void jTA1MouseReleased(java.awt.event.MouseEvent evt) {                                   
        mouseAction(evt);
      }                                  
    
      private void mouseAction(java.awt.event.MouseEvent evt) {
        String s;
        int button, count, id, mask;
        button = evt.getButton();
        count = evt.getClickCount();
        mask=evt.getModifiersEx();
        id = evt.getID();
    
        switch (button) {
          case MouseEvent.BUTTON1:
            s = "Button 1 ";
            break;
    
          case MouseEvent.BUTTON2:
            s = "Button 2 ";
            break;
    
          case MouseEvent.BUTTON3:
            s = "Button 3 ";
            break;
    
          default:
            throw new AssertionError();
        }
    
        switch (id) {
          case MouseEvent.MOUSE_CLICKED:
            s += "clicked ";
            break;
    
          case MouseEvent.MOUSE_PRESSED:
            s += "pressed ";
            break;
    
          case MouseEvent.MOUSE_RELEASED:
            s += "released ";
            break;
    
          default:
            throw new AssertionError();
        }
    
        s += "count=" + count;
    
        if ((mask & InputEvent.ALT_GRAPH_DOWN_MASK) !=0) {
          s+=" Alt-Gr";
        }
        if ((mask & InputEvent.ALT_DOWN_MASK) !=0) {
          s+=" Alt";
        }
        if ((mask & InputEvent.CTRL_DOWN_MASK) !=0) {
          s+=" Ctrl";
        }
        if ((mask & InputEvent.META_DOWN_MASK) !=0) {
          s+=" Meta";
        }
        if ((mask & InputEvent.SHIFT_DOWN_MASK) !=0) {
          s+=" Shift";
        }
    //    if ((mask & InputEvent.BUTTON1_DOWN_MASK) !=0) {
    //      s+=" Button1";
    //    }
    //    if ((mask & InputEvent.BUTTON2_DOWN_MASK) !=0) {
    //      s+=" Button2";
    //    }
    //    if ((mask & InputEvent.BUTTON3_DOWN_MASK) !=0) {
    //      s+=" Button3";
    //    }
        s+="\n";
        jTA1.append(s);
    
      }
    
      /**
       * @param args the command line arguments
       */
      public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
          for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
              javax.swing.UIManager.setLookAndFeel(info.getClassName());
              break;
            }
          }
        } catch (ClassNotFoundException ex) {
          java.util.logging.Logger.getLogger(MouseCLick.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
          java.util.logging.Logger.getLogger(MouseCLick.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
          java.util.logging.Logger.getLogger(MouseCLick.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
          java.util.logging.Logger.getLogger(MouseCLick.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
    
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
            new MouseCLick().setVisible(true);
          }
        });
      }
      // Variables declaration - do not modify                     
      private javax.swing.JScrollPane jScrollPane2;
      private javax.swing.JTextArea jTA1;
      // End of variables declaration                   
    }
  • 3. Re: Problem with mouse events and getModifiersEx
    jtahlborn Expert
    Currently Being Moderated
    what OS are you on?
  • 4. Re: Problem with mouse events and getModifiersEx
    ptoye Newbie
    Currently Being Moderated
    Sorry should have said - Windows 7 Home 64-bit.
  • 5. Re: Problem with mouse events and getModifiersEx
    ptoye Newbie
    Currently Being Moderated
    What - no-one?

    Since posting I've written a similar program in VB and that gives the expected results. But there's nothing in VB to test the Windows (=Meta?) key.

    Edited by: ptoye on May 15, 2013 7:32 AM
  • 6. Re: Problem with mouse events and getModifiersEx
    gimbal2 Guru
    Currently Being Moderated
    on my Windows 7 laptop it reports 8 buttons; there are only three however.

    And I get the exact same odd behavior as you do... only under a slightly older version of Java 6 (32), so if there is a problem it has been around for a while. What I find increasingly odder is that I cannot find reports of other people running into this in Google. But on the other hand I also see a bare minimum of examples that even touch getModifiersEx() and in all my Swing projects I have never even considered using it; I always deal with keyboard and mouse state handling separately. Perhaps you're doing something here not many others would consider doing and thus this has gone unnoticed.
  • 7. Re: Problem with mouse events and getModifiersEx
    mKorbel Explorer
    Currently Being Moderated
    This is more an API than a programming issue, but I can't find a suitable forum there.

    - [one of suitable](Swing

    What - no-one?

    - [answer is (as always) in API or in official tutorials](http://docs.oracle.com/javase/7/docs/api/java/awt/event/MouseEvent.html#getButton%28%29) , reserved for BackMouseButton and ForwardMouseButton

    - if isn't there multiple Keyboard and Mouse short_Cuts(together), then to use methods implemented in SwingUtilities.isLeftMouse...

    - if yes then to use AWTEventListener
  • 8. Re: Problem with mouse events and getModifiersEx
    gimbal2 Guru
    Currently Being Moderated
    mKorbel wrote:
    - [answer is (as always) in API or in official tutorials](http://docs.oracle.com/javase/7/docs/api/java/awt/event/MouseEvent.html#getButton%28%29) , reserved for BackMouseButton and ForwardMouseButton

    - if isn't there multiple Keyboard and Mouse short_Cuts(together), then to use methods implemented in SwingUtilities.isLeftMouse...

    - if yes then to use AWTEventListener
    And what exactly is this vague blob of text the answer to?
  • 9. Re: Problem with mouse events and getModifiersEx
    ptoye Newbie
    Currently Being Moderated
    In that case it's presumably a bug. But whether Oracle will do anything about it is anyone's guess. I'll try.....

    Yes, it's possible to process keys and mouse events separately, but that can give different results. Consider:

    With the focus outside the window that the program owns, press "ctrl". Move the mouse into the window and click on something. You won't get the keypress, but you will get the mouse click. My program wants to know if the Ctrl key was down at the point that the mouse was clicked. As, I suspect, do most programs.

    However, I've found that I've not got the latest release (7u21) of Java, but am having some difficulty in downloading it, which I'll report elsewhere here. I doubt if it will make much difference, though.

    Edited by: ptoye on May 16, 2013 3:49 AM

    [Later] I also fails under the latest release. I've reported it as Java bug. Bug Id: 9002718 if anyone's interested.

    Edited by: ptoye on May 18, 2013 4:00 AM
  • 10. Re: Problem with mouse events and getModifiersEx
    ptoye Newbie
    Currently Being Moderated
    mKorbel wrote:
    This is more an API than a programming issue, but I can't find a suitable forum there.

    - [one of suitable](Swing

    What - no-one?

    - [answer is (as always) in API or in official tutorials](http://docs.oracle.com/javase/7/docs/api/java/awt/event/MouseEvent.html#getButton%28%29) , reserved for BackMouseButton and ForwardMouseButton

    - if isn't there multiple Keyboard and Mouse short_Cuts(together), then to use methods implemented in SwingUtilities.isLeftMouse...

    - if yes then to use AWTEventListener
    I agree that it's an API issue - see my initial post.

    I don't understand the rest of your comment, I'm afraid.
  • 11. Re: Problem with mouse events and getModifiersEx
    mKorbel Explorer
    Currently Being Moderated
    - for events generated only from Mouse to use methods implemented in SwingUtilities API in events fired from Mouse(Xxx)Listener

    - for combination of key and mouse (CTRL + RIGHT_MOUSE_BUTTON) events to use AWTEventListener
  • 12. Re: Problem with mouse events and getModifiersEx
    ptoye Newbie
    Currently Being Moderated
    mKorbel wrote:
    - for events generated only from Mouse to use methods implemented in SwingUtilities API in events fired from Mouse(Xxx)Listener

    - for combination of key and mouse (CTRL + RIGHT_MOUSE_BUTTON) events to use AWTEventListener
    Sorry, this doesn't make sense. Are you trying to point out a workaround? My point is that the the API doesn't conform to the documentation.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points