API Overview API Index Package Overview Direct link to this page
JDK 1.6
  javax.swing.plaf.basic. BasicMenuUI View Javadoc
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608

/*
 * @(#)BasicMenuUI.java	1.162 05/11/30
 *
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package javax.swing.plaf.basic;

import sun.swing.DefaultLookup;
import sun.swing.UIAction;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.plaf.*;
import javax.swing.border.*;
import java.util.Arrays;
import java.util.ArrayList;


/**
 * A default L&F implementation of MenuUI.  This implementation 
 * is a "combined" view/controller.
 *
 * @version 1.162 11/30/05
 * @author Georges Saab
 * @author David Karlton
 * @author Arnaud Weber
 */
public class BasicMenuUI extends BasicMenuItemUI 
{
    protected ChangeListener         changeListener;
    protected MenuListener           menuListener;

    private int lastMnemonic = 0;

    /** Uses as the parent of the windowInputMap when selected. */
    private InputMap selectedWindowInputMap;

    /* diagnostic aids -- should be false for production builds. */
    private static final boolean TRACE =   false; // trace creates and disposes
    private static final boolean VERBOSE = false; // show reuse hits/misses
    private static final boolean DEBUG =   false;  // show bad params, misc.

    private static boolean crossMenuMnemonic = true;

    public static ComponentUI createUI(JComponent x) {
	return new BasicMenuUI();
    }

    static void loadActionMap(LazyActionMap map) {
        BasicMenuItemUI.loadActionMap(map);
        map.put(new Actions(Actions.SELECT, null, true));
    }


    protected void installDefaults() {
	super.installDefaults();
	updateDefaultBackgroundColor();
	((JMenu)menuItem).setDelay(200);
        crossMenuMnemonic = UIManager.getBoolean("Menu.crossMenuMnemonic");
    }

    protected String getPropertyPrefix() {
	return "Menu";
    }

    protected void installListeners() {
	super.installListeners();

	if (changeListener == null)
	    changeListener = createChangeListener(menuItem);

	if (changeListener != null)
	    menuItem.addChangeListener(changeListener);

	if (menuListener == null)
	    menuListener = createMenuListener(menuItem);

	if (menuListener != null)
	    ((JMenu)menuItem).addMenuListener(menuListener);
    }

    protected void installKeyboardActions() {
	super.installKeyboardActions();
	updateMnemonicBinding();
    }

    void installLazyActionMap() {
        LazyActionMap.installLazyActionMap(menuItem, BasicMenuUI.class,
                                           getPropertyPrefix() + ".actionMap");
    }

    void updateMnemonicBinding() {
	int mnemonic = menuItem.getModel().getMnemonic();
        int[] shortcutKeys = (int[])DefaultLookup.get(menuItem, this,
                                                   "Menu.shortcutKeys");
        if (shortcutKeys == null) {
            shortcutKeys = new int[] {KeyEvent.ALT_MASK};
        }
	if (mnemonic == lastMnemonic) {
	    return;
	}
        InputMap windowInputMap = SwingUtilities.getUIInputMap(
                       menuItem, JComponent.WHEN_IN_FOCUSED_WINDOW);
	if (lastMnemonic != 0 && windowInputMap != null) {
            for (int i=0; i<shortcutKeys.length; i++) {
                windowInputMap.remove(KeyStroke.getKeyStroke
                                      (lastMnemonic, shortcutKeys[i], false));
            }
	}
	if (mnemonic != 0) {
	    if (windowInputMap == null) {
		windowInputMap = createInputMap(JComponent.
					      WHEN_IN_FOCUSED_WINDOW);
		SwingUtilities.replaceUIInputMap(menuItem, JComponent.
				       WHEN_IN_FOCUSED_WINDOW, windowInputMap);
	    }
            for (int i=0; i<shortcutKeys.length; i++) {
                windowInputMap.put(KeyStroke.getKeyStroke(mnemonic,
                                         shortcutKeys[i], false),
                                   "selectMenu");
            }
        }
	lastMnemonic = mnemonic;
    }

    protected void uninstallKeyboardActions() {
	super.uninstallKeyboardActions();
        lastMnemonic = 0;
    }

    protected MouseInputListener createMouseInputListener(JComponent c) {
	return getHandler();
    }

    protected MenuListener createMenuListener(JComponent c) {
	return null;
    }

    protected ChangeListener createChangeListener(JComponent c) {
	return null;
    }

    protected PropertyChangeListener createPropertyChangeListener(JComponent c) {
        return getHandler();
    }

    BasicMenuItemUI.Handler getHandler() {
        if (handler == null) {
            handler = new Handler();
        }
        return handler;
    }

    protected void uninstallDefaults() {
	menuItem.setArmed(false);
	menuItem.setSelected(false);
	menuItem.resetKeyboardActions();
	super.uninstallDefaults();
    }

    protected void uninstallListeners() {
	super.uninstallListeners();

	if (changeListener != null)
	    menuItem.removeChangeListener(changeListener);

	if (menuListener != null)
	    ((JMenu)menuItem).removeMenuListener(menuListener);

	changeListener = null;
	menuListener = null;
        handler = null;
    }

    protected MenuDragMouseListener createMenuDragMouseListener(JComponent c) {
	return getHandler();
    }
    
    protected MenuKeyListener createMenuKeyListener(JComponent c) {
	return (MenuKeyListener)getHandler();
    }

    public Dimension getMaximumSize(JComponent c) {
	if (((JMenu)menuItem).isTopLevelMenu() == true) {
	    Dimension d = c.getPreferredSize();
	    return new Dimension(d.width, Short.MAX_VALUE);
	}
        return null;
    }

    protected void setupPostTimer(JMenu menu) {
        Timer timer = new Timer(menu.getDelay(), new Actions(
                                    Actions.SELECT, menu,false));
        timer.setRepeats(false);
        timer.start();
    }

    private static void appendPath(MenuElement[] path, MenuElement elem) {
        MenuElement newPath[] = new MenuElement[path.length+1];
        System.arraycopy(path, 0, newPath, 0, path.length);
        newPath[path.length] = elem;
        MenuSelectionManager.defaultManager().setSelectedPath(newPath);
    }

    private static class Actions extends UIAction {
        private static final String SELECT = "selectMenu";

        // NOTE: This will be null if the action is registered in the
        // ActionMap. For the timer use it will be non-null.
	private JMenu menu;
        private boolean force=false;

        Actions(String key, JMenu menu, boolean shouldForce) {
            super(key);
	    this.menu = menu;
            this.force = shouldForce;
	}
	
        private JMenu getMenu(ActionEvent e) {
            if (e.getSource() instanceof JMenu) {
                return (JMenu)e.getSource();
            }
            return menu;
        }

	public void actionPerformed(ActionEvent e) {
            JMenu menu = getMenu(e);
            if (!crossMenuMnemonic) {
                JPopupMenu pm = BasicPopupMenuUI.getLastPopup();
                if (pm != null && pm != menu.getParent()) {
                    return;
                }
            }

	    final MenuSelectionManager defaultManager = MenuSelectionManager.defaultManager();
            if(force) {
                Container cnt = menu.getParent();
                if(cnt != null && cnt instanceof JMenuBar) {
                    MenuElement me[];
                    MenuElement subElements[];
		    
                    subElements = menu.getPopupMenu().getSubElements();
                    if(subElements.length > 0) {
                        me = new MenuElement[4];
                        me[0] = (MenuElement) cnt;
                        me[1] = (MenuElement) menu;
                        me[2] = (MenuElement) menu.getPopupMenu();
                        me[3] = subElements[0];
                    } else {
                        me = new MenuElement[3];
                        me[0] = (MenuElement)cnt;
                        me[1] = menu;
                        me[2] = (MenuElement) menu.getPopupMenu();
                    }
                    defaultManager.setSelectedPath(me);
		}
            } else {
                MenuElement path[] = defaultManager.getSelectedPath();
                if(path.length > 0 && path[path.length-1] == menu) {
                    appendPath(path, menu.getPopupMenu());
                }
            }
        }

	public boolean isEnabled(Object c) {
            if (c instanceof JMenu) {
                return ((JMenu)c).isEnabled();
            }
            return true;
	}
    }

    /*
     * Set the background color depending on whether this is a toplevel menu
     * in a menubar or a submenu of another menu.
     */
    private void updateDefaultBackgroundColor() {
	if (!UIManager.getBoolean("Menu.useMenuBarBackgroundForTopLevel")) {
	   return;
	}
	JMenu menu = (JMenu)menuItem;
	if (menu.getBackground() instanceof UIResource) {
	    if (menu.isTopLevelMenu()) {
		menu.setBackground(UIManager.getColor("MenuBar.background"));
	    } else {
		menu.setBackground(UIManager.getColor(getPropertyPrefix() + ".background"));
	    }
	}		    
    }

    /**
     * Instantiated and used by a menu item to handle the current menu selection
     * from mouse events. A MouseInputHandler processes and forwards all mouse events
     * to a shared instance of the MenuSelectionManager. 
     * <p>
     * This class is protected so that it can be subclassed by other look and
     * feels to implement their own mouse handling behavior. All overridden
     * methods should call the parent methods so that the menu selection
     * is correct.
     *
     * @see javax.swing.MenuSelectionManager
     * @since 1.4
     */
    protected class MouseInputHandler implements MouseInputListener {
        // NOTE: This class exists only for backward compatability. All
        // its functionality has been moved into Handler. If you need to add
        // new functionality add it to the Handler, but make sure this
        // class calls into the Handler.

	public void mouseClicked(MouseEvent e) {
            getHandler().mouseClicked(e);
        }

	/**
	 * Invoked when the mouse has been clicked on the menu. This
	 * method clears or sets the selection path of the
	 * MenuSelectionManager.
	 * 
	 * @param e the mouse event
	 */
        public void mousePressed(MouseEvent e) {
            getHandler().mousePressed(e);
        }

	/**
	 * Invoked when the mouse has been released on the menu. Delegates the 
	 * mouse event to the MenuSelectionManager.
	 *
	 * @param e the mouse event
	 */
	public void mouseReleased(MouseEvent e) {
            getHandler().mouseReleased(e);
	}

	/**
	 * Invoked when the cursor enters the menu. This method sets the selected
	 * path for the MenuSelectionManager and handles the case
	 * in which a menu item is used to pop up an additional menu, as in a 
	 * hierarchical menu system.
	 * 
	 * @param e the mouse event; not used
	 */ 
	public void mouseEntered(MouseEvent e) {
            getHandler().mouseEntered(e);
	}
	public void mouseExited(MouseEvent e) {
            getHandler().mouseExited(e);
	}
	
	/**
	 * Invoked when a mouse button is pressed on the menu and then dragged.
	 * Delegates the mouse event to the MenuSelectionManager.
	 *
	 * @param e the mouse event
	 * @see java.awt.event.MouseMotionListener#mouseDragged
	 */
	public void mouseDragged(MouseEvent e) {
            getHandler().mouseDragged(e);
	}

	public void mouseMoved(MouseEvent e) {
            getHandler().mouseMoved(e);
	}
    }

    /**
     * As of Java 2 platform 1.4, this previously undocumented class
     * is now obsolete. KeyBindings are now managed by the popup menu.
     */
    public class ChangeHandler implements ChangeListener {
        public JMenu    menu;
	public BasicMenuUI ui;
        public boolean  isSelected = false;
        public Component wasFocused;

        public ChangeHandler(JMenu m, BasicMenuUI ui) {
            menu = m;
            this.ui = ui;
        }

        public void stateChanged(ChangeEvent e) { }
    }

    private class Handler extends BasicMenuItemUI.Handler implements
            MenuKeyListener {
        //
        // PropertyChangeListener
        //
        public void propertyChange(PropertyChangeEvent e) {
	    if (e.getPropertyName() == AbstractButton.
                             MNEMONIC_CHANGED_PROPERTY) {
                updateMnemonicBinding();
	    }
            else {
		if (e.getPropertyName().equals("ancestor")) {
		    updateDefaultBackgroundColor();
	        }
                super.propertyChange(e);
            }
	}

        //
        // MouseInputListener
        //
	public void mouseClicked(MouseEvent e) {
        }

	/**
	 * Invoked when the mouse has been clicked on the menu. This
	 * method clears or sets the selection path of the
	 * MenuSelectionManager.
	 * 
	 * @param e the mouse event
	 */
        public void mousePressed(MouseEvent e) {
	    JMenu menu = (JMenu)menuItem;
	    if (!menu.isEnabled())
		return;

	    MenuSelectionManager manager = 
		MenuSelectionManager.defaultManager();
            if(menu.isTopLevelMenu()) {
		if(menu.isSelected()) {
		    manager.clearSelectedPath();
		} else {
		    Container cnt = menu.getParent();
		    if(cnt != null && cnt instanceof JMenuBar) {
			MenuElement me[] = new MenuElement[2];
			me[0]=(MenuElement)cnt;
			me[1]=menu;
			manager.setSelectedPath(me);
		    }
		}
	    }

            MenuElement selectedPath[] = manager.getSelectedPath();
            if (selectedPath.length > 0 && 
                selectedPath[selectedPath.length-1] != menu.getPopupMenu()) {

		if(menu.isTopLevelMenu() || 
		   menu.getDelay() == 0) {
                    appendPath(selectedPath, menu.getPopupMenu());
		} else {
		    setupPostTimer(menu);
		}
            }
        }

	/**
	 * Invoked when the mouse has been released on the menu. Delegates the 
	 * mouse event to the MenuSelectionManager.
	 *
	 * @param e the mouse event
	 */
	public void mouseReleased(MouseEvent e) {
	    JMenu menu = (JMenu)menuItem;
	    if (!menu.isEnabled())
		return;
	    MenuSelectionManager manager = 
		MenuSelectionManager.defaultManager();
	    manager.processMouseEvent(e);
	    if (!e.isConsumed())
		manager.clearSelectedPath();		
	}

	/**
	 * Invoked when the cursor enters the menu. This method sets the selected
	 * path for the MenuSelectionManager and handles the case
	 * in which a menu item is used to pop up an additional menu, as in a 
	 * hierarchical menu system.
	 * 
	 * @param e the mouse event; not used
	 */ 
	public void mouseEntered(MouseEvent e) {
	    JMenu menu = (JMenu)menuItem;
            // only disable the menu highlighting if it's disabled and the property isn't
            // true. This allows disabled rollovers to work in WinL&F
            if (!menu.isEnabled() && !UIManager.getBoolean("MenuItem.disabledAreNavigable")) {
                return;
            }

	    MenuSelectionManager manager = 
		MenuSelectionManager.defaultManager();
	    MenuElement selectedPath[] = manager.getSelectedPath();	    
	    if (!menu.isTopLevelMenu()) {
		if(!(selectedPath.length > 0 && 
		     selectedPath[selectedPath.length-1] == 
		     menu.getPopupMenu())) {
		    if(menu.getDelay() == 0) {
                        appendPath(getPath(), menu.getPopupMenu());
                    } else {
			manager.setSelectedPath(getPath());
			setupPostTimer(menu);
		    }
		}
	    } else {
		if(selectedPath.length > 0 &&
		   selectedPath[0] == menu.getParent()) {
		    MenuElement newPath[] = new MenuElement[3];
		    // A top level menu's parent is by definition 
		    // a JMenuBar
		    newPath[0] = (MenuElement)menu.getParent();
		    newPath[1] = menu;
		    newPath[2] = menu.getPopupMenu();
		    manager.setSelectedPath(newPath);
		}
	    }
	}
	public void mouseExited(MouseEvent e) {
	}
	
	/**
	 * Invoked when a mouse button is pressed on the menu and then dragged.
	 * Delegates the mouse event to the MenuSelectionManager.
	 *
	 * @param e the mouse event
	 * @see java.awt.event.MouseMotionListener#mouseDragged
	 */
	public void mouseDragged(MouseEvent e) {
	    JMenu menu = (JMenu)menuItem;
	    if (!menu.isEnabled())
		return;
	    MenuSelectionManager.defaultManager().processMouseEvent(e);
	}
	public void mouseMoved(MouseEvent e) {
	}


        //
        // MenuDragHandler
        //
	public void menuDragMouseEntered(MenuDragMouseEvent e) {}
	public void menuDragMouseDragged(MenuDragMouseEvent e) {
	    if (menuItem.isEnabled() == false)
		return;
	    
	    MenuSelectionManager manager = e.getMenuSelectionManager();
	    MenuElement path[] = e.getPath();
	    
	    Point p = e.getPoint();
	    if(p.x >= 0 && p.x < menuItem.getWidth() &&
	       p.y >= 0 && p.y < menuItem.getHeight()) {
		JMenu menu = (JMenu)menuItem;
		MenuElement selectedPath[] = manager.getSelectedPath();
		if(!(selectedPath.length > 0 && 
		     selectedPath[selectedPath.length-1] == 
		     menu.getPopupMenu())) {
		    if(menu.isTopLevelMenu() || 
		       menu.getDelay() == 0  ||
		       e.getID() == MouseEvent.MOUSE_DRAGGED) {
                        appendPath(path, menu.getPopupMenu());
		    } else {
			manager.setSelectedPath(path);
			setupPostTimer(menu);
		    }
		}
	    } else if(e.getID() == MouseEvent.MOUSE_RELEASED) {
		Component comp = manager.componentForPoint(e.getComponent(), e.getPoint());
		if (comp == null)
		    manager.clearSelectedPath();
	    }
	    
	}
	public void menuDragMouseExited(MenuDragMouseEvent e) {}
	public void menuDragMouseReleased(MenuDragMouseEvent e) {}	    


        //
        // MenuKeyListener
        //
	/**
	 * Open the Menu
	 */
	public void menuKeyTyped(MenuKeyEvent e) {
            if (!crossMenuMnemonic && BasicPopupMenuUI.getLastPopup() != null) {
                // when crossMenuMnemonic is not set, we don't open a toplevel
                // menu if another toplevel menu is already open
                    return;
                }

            char key = Character.toLowerCase((char)menuItem.getMnemonic());
            MenuElement path[] = e.getPath();
            if (key == Character.toLowerCase(e.getKeyChar())) {
                JPopupMenu popupMenu = ((JMenu)menuItem).getPopupMenu();
                ArrayList newList = new ArrayList(Arrays.asList(path));
                newList.add(popupMenu);
                MenuElement subs[] = popupMenu.getSubElements();
                MenuElement sub =
                        BasicPopupMenuUI.findEnabledChild(subs, -1, true);
                if(sub != null) {
                    newList.add(sub);
                }
                MenuSelectionManager manager = e.getMenuSelectionManager();
                MenuElement newPath[] = new MenuElement[0];;
                newPath = (MenuElement[]) newList.toArray(newPath);
                manager.setSelectedPath(newPath);
                e.consume();
            }
        }

        public void menuKeyPressed(MenuKeyEvent e) {}
	public void menuKeyReleased(MenuKeyEvent e) {}
    }
}

Generated By: JavaOnTracks Doclet 0.1.4     ©Thibaut Colar