Popup Menus and the Mac OS

Today I was evaluating a demo that someone had graciously submitted for the tutorial. This demo features a good use of a popup menu but, for some reason, it wasn't working on my Mac. Here is a snippet of code from the demo. Can you see what's wrong?

    /\*\*
     \* Selects the closest path on a right click and bring up the operations menu.
     \*/
    private MouseAdapter treeMenuClicked = new MouseAdapter(){
        /\*\*
         \* @see java.awt.event.MouseAdapter#mouseClicked(java.awt.event.MouseEvent)
         \*/
        public void mouseClicked(MouseEvent e) {
            if(e.getButton() == MouseEvent.BUTTON3){
                int row = tree.getClosestRowForLocation(e.getX(), e.getY());
                tree.setSelectionPath(tree.getPathForRow(row));
                menu.show(tree, e.getX(), e.getY());
            }
        }
    };

You probably guessed that this is non-portable code. It's checking for "button 3" which my Mac mouse doesn't have. I'm happy to say that the How to Use Menus section of the Java Tutorial actually addresses this: replace the previous code with this code:

    private MouseAdapter treeMenuClicked = new PopupListener();
    
    class PopupListener extends MouseAdapter {
        public void mousePressed(MouseEvent e) {
            maybeShowPopup(e);
        }

        public void mouseReleased(MouseEvent e) {
            maybeShowPopup(e);
        }

        private void maybeShowPopup(MouseEvent e) {
            if (e.isPopupTrigger()) {
                int row = tree.getClosestRowForLocation(e.getX(), e.getY());
                tree.setSelectionPath(tree.getPathForRow(row));
                menu.show(tree, e.getX(), e.getY());
            }
        }
    }

Now I can bring up the popup menu on my Mac using Control-click. This example should now work on all platforms. (Though I can only test it on my Mac. Please let me know if it doesn't work for you!)

-- Sharon Zakhour

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

Blog about Java technology documentation and news about Java releases.

Search

Categories
Archives
« July 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  
       
Today