rev 47462 : Fixed JDK-8178430: JMenu in GridBagLayout flickers when label text shows "..."
and is updated.
***
JDK-8178430: Fixed following issues with the test:
1. Throw exception in case the menu bar size is not proper.
2. Run the test for about 10 seconds, and then automatically
close the window.

   1 /*
   2  * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package javax.swing.plaf.basic;
  27 
  28 import java.awt.*;
  29 import java.awt.event.*;
  30 import java.beans.PropertyChangeEvent;
  31 import java.beans.PropertyChangeListener;
  32 
  33 import javax.swing.*;
  34 import javax.swing.event.*;
  35 import javax.swing.plaf.*;
  36 import javax.swing.text.View;
  37 
  38 import sun.swing.*;
  39 
  40 /**
  41  * BasicMenuItem implementation
  42  *
  43  * @author Georges Saab
  44  * @author David Karlton
  45  * @author Arnaud Weber
  46  * @author Fredrik Lagerblad
  47  */
  48 public class BasicMenuItemUI extends MenuItemUI
  49 {
  50     /**
  51      * The instance of {@code JMenuItem}.
  52      */
  53     protected JMenuItem menuItem = null;
  54     /**
  55      * The color of the selection background.
  56      */
  57     protected Color selectionBackground;
  58     /**
  59      * The color of the selection foreground.
  60      */
  61     protected Color selectionForeground;
  62     /**
  63      * The color of the disabled foreground.
  64      */
  65     protected Color disabledForeground;
  66     /**
  67      * The color of the accelerator foreground.
  68      */
  69     protected Color acceleratorForeground;
  70     /**
  71      * The color of the accelerator selection.
  72      */
  73     protected Color acceleratorSelectionForeground;
  74 
  75     /**
  76      * Accelerator delimiter string, such as {@code '+'} in {@code 'Ctrl+C'}.
  77      * @since 1.7
  78      */
  79     protected String acceleratorDelimiter;
  80 
  81     /**
  82      * The gap between the text and the icon.
  83      */
  84     protected int defaultTextIconGap;
  85     /**
  86      * The accelerator font.
  87      */
  88     protected Font acceleratorFont;
  89 
  90     /**
  91      * The instance of {@code MouseInputListener}.
  92      */
  93     protected MouseInputListener mouseInputListener;
  94     /**
  95      * The instance of {@code MenuDragMouseListener}.
  96      */
  97     protected MenuDragMouseListener menuDragMouseListener;
  98     /**
  99      * The instance of {@code MenuKeyListener}.
 100      */
 101     protected MenuKeyListener menuKeyListener;
 102     /**
 103      * {@code PropertyChangeListener} returned from
 104      * {@code createPropertyChangeListener}. You should not
 105      * need to access this field, rather if you want to customize the
 106      * {@code PropertyChangeListener} override
 107      * {@code createPropertyChangeListener}.
 108      *
 109      * @since 1.6
 110      * @see #createPropertyChangeListener
 111      */
 112     protected PropertyChangeListener propertyChangeListener;
 113     // BasicMenuUI also uses this.
 114     Handler handler;
 115     /**
 116      * The arrow icon.
 117      */
 118     protected Icon arrowIcon = null;
 119     /**
 120      * The check icon.
 121      */
 122     protected Icon checkIcon = null;
 123     /**
 124      * The value represents if the old border is painted.
 125      */
 126     protected boolean oldBorderPainted;
 127 
 128     /* diagnostic aids -- should be false for production builds. */
 129     private static final boolean TRACE =   false; // trace creates and disposes
 130 
 131     private static final boolean VERBOSE = false; // show reuse hits/misses
 132     private static final boolean DEBUG =   false;  // show bad params, misc.
 133 
 134     static void loadActionMap(LazyActionMap map) {
 135         // NOTE: BasicMenuUI also calls into this method.
 136         map.put(new Actions(Actions.CLICK));
 137         BasicLookAndFeel.installAudioActionMap(map);
 138     }
 139 
 140     /**
 141      * Returns a new instance of {@code BasicMenuItemUI}.
 142      *
 143      * @param c a component
 144      * @return a new instance of {@code BasicMenuItemUI}
 145      */
 146     public static ComponentUI createUI(JComponent c) {
 147         return new BasicMenuItemUI();
 148     }
 149 
 150     public void installUI(JComponent c) {
 151         menuItem = (JMenuItem) c;
 152 
 153         installDefaults();
 154         installComponents(menuItem);
 155         installListeners();
 156         installKeyboardActions();
 157     }
 158 
 159     /**
 160      * Installs default properties.
 161      */
 162     protected void installDefaults() {
 163         String prefix = getPropertyPrefix();
 164 
 165         acceleratorFont = UIManager.getFont("MenuItem.acceleratorFont");
 166         // use default if missing so that BasicMenuItemUI can be used in other
 167         // LAFs like Nimbus
 168         if (acceleratorFont == null) {
 169             acceleratorFont = UIManager.getFont("MenuItem.font");
 170         }
 171 
 172         Object opaque = UIManager.get(getPropertyPrefix() + ".opaque");
 173         if (opaque != null) {
 174             LookAndFeel.installProperty(menuItem, "opaque", opaque);
 175         }
 176         else {
 177             LookAndFeel.installProperty(menuItem, "opaque", Boolean.TRUE);
 178         }
 179         if(menuItem.getMargin() == null ||
 180            (menuItem.getMargin() instanceof UIResource)) {
 181             menuItem.setMargin(UIManager.getInsets(prefix + ".margin"));
 182         }
 183 
 184         LookAndFeel.installProperty(menuItem, "iconTextGap", Integer.valueOf(4));
 185         defaultTextIconGap = menuItem.getIconTextGap();
 186 
 187         LookAndFeel.installBorder(menuItem, prefix + ".border");
 188         oldBorderPainted = menuItem.isBorderPainted();
 189         LookAndFeel.installProperty(menuItem, "borderPainted",
 190                                     UIManager.getBoolean(prefix + ".borderPainted"));
 191         LookAndFeel.installColorsAndFont(menuItem,
 192                                          prefix + ".background",
 193                                          prefix + ".foreground",
 194                                          prefix + ".font");
 195 
 196         // MenuItem specific defaults
 197         if (selectionBackground == null ||
 198             selectionBackground instanceof UIResource) {
 199             selectionBackground =
 200                 UIManager.getColor(prefix + ".selectionBackground");
 201         }
 202         if (selectionForeground == null ||
 203             selectionForeground instanceof UIResource) {
 204             selectionForeground =
 205                 UIManager.getColor(prefix + ".selectionForeground");
 206         }
 207         if (disabledForeground == null ||
 208             disabledForeground instanceof UIResource) {
 209             disabledForeground =
 210                 UIManager.getColor(prefix + ".disabledForeground");
 211         }
 212         if (acceleratorForeground == null ||
 213             acceleratorForeground instanceof UIResource) {
 214             acceleratorForeground =
 215                 UIManager.getColor(prefix + ".acceleratorForeground");
 216         }
 217         if (acceleratorSelectionForeground == null ||
 218             acceleratorSelectionForeground instanceof UIResource) {
 219             acceleratorSelectionForeground =
 220                 UIManager.getColor(prefix + ".acceleratorSelectionForeground");
 221         }
 222         // Get accelerator delimiter
 223         acceleratorDelimiter =
 224             UIManager.getString("MenuItem.acceleratorDelimiter");
 225         if (acceleratorDelimiter == null) { acceleratorDelimiter = "+"; }
 226         // Icons
 227         if (arrowIcon == null ||
 228             arrowIcon instanceof UIResource) {
 229             arrowIcon = UIManager.getIcon(prefix + ".arrowIcon");
 230         }
 231         updateCheckIcon();
 232     }
 233 
 234     /**
 235      * Updates check Icon based on column layout
 236      */
 237     private void updateCheckIcon() {
 238         String prefix = getPropertyPrefix();
 239 
 240         if (checkIcon == null ||
 241             checkIcon instanceof UIResource) {
 242             checkIcon = UIManager.getIcon(prefix + ".checkIcon");
 243             //In case of column layout, .checkIconFactory is defined for this UI,
 244             //the icon is compatible with it and useCheckAndArrow() is true,
 245             //then the icon is handled by the checkIcon.
 246             boolean isColumnLayout = MenuItemLayoutHelper.isColumnLayout(
 247                     BasicGraphicsUtils.isLeftToRight(menuItem), menuItem);
 248             if (isColumnLayout) {
 249                 MenuItemCheckIconFactory iconFactory =
 250                         (MenuItemCheckIconFactory) UIManager.get(prefix
 251                                 + ".checkIconFactory");
 252                 if (iconFactory != null
 253                         && MenuItemLayoutHelper.useCheckAndArrow(menuItem)
 254                         && iconFactory.isCompatible(checkIcon, prefix)) {
 255                     checkIcon = iconFactory.getIcon(menuItem);
 256                 }
 257             }
 258         }
 259     }
 260 
 261     /**
 262      *
 263      * @param menuItem a menu item
 264      * @since 1.3
 265      */
 266     protected void installComponents(JMenuItem menuItem){
 267         BasicHTML.updateRenderer(menuItem, menuItem.getText());
 268     }
 269 
 270     /**
 271      * Returns a property prefix.
 272      *
 273      * @return a property prefix
 274      */
 275     protected String getPropertyPrefix() {
 276         return "MenuItem";
 277     }
 278 
 279     /**
 280      * Registers listeners.
 281      */
 282     protected void installListeners() {
 283         if ((mouseInputListener = createMouseInputListener(menuItem)) != null) {
 284             menuItem.addMouseListener(mouseInputListener);
 285             menuItem.addMouseMotionListener(mouseInputListener);
 286         }
 287         if ((menuDragMouseListener = createMenuDragMouseListener(menuItem)) != null) {
 288             menuItem.addMenuDragMouseListener(menuDragMouseListener);
 289         }
 290         if ((menuKeyListener = createMenuKeyListener(menuItem)) != null) {
 291             menuItem.addMenuKeyListener(menuKeyListener);
 292         }
 293         if ((propertyChangeListener = createPropertyChangeListener(menuItem)) != null) {
 294             menuItem.addPropertyChangeListener(propertyChangeListener);
 295         }
 296     }
 297 
 298     /**
 299      * Registers keyboard action.
 300      */
 301     protected void installKeyboardActions() {
 302         installLazyActionMap();
 303         updateAcceleratorBinding();
 304     }
 305 
 306     void installLazyActionMap() {
 307         LazyActionMap.installLazyActionMap(menuItem, BasicMenuItemUI.class,
 308                                            getPropertyPrefix() + ".actionMap");
 309     }
 310 
 311     public void uninstallUI(JComponent c) {
 312         menuItem = (JMenuItem)c;
 313         uninstallDefaults();
 314         uninstallComponents(menuItem);
 315         uninstallListeners();
 316         uninstallKeyboardActions();
 317         MenuItemLayoutHelper.clearUsedParentClientProperties(menuItem);
 318         menuItem = null;
 319     }
 320 
 321     /**
 322      * Uninstalls default properties.
 323      */
 324     protected void uninstallDefaults() {
 325         LookAndFeel.uninstallBorder(menuItem);
 326         LookAndFeel.installProperty(menuItem, "borderPainted", oldBorderPainted);
 327         if (menuItem.getMargin() instanceof UIResource)
 328             menuItem.setMargin(null);
 329         if (arrowIcon instanceof UIResource)
 330             arrowIcon = null;
 331         if (checkIcon instanceof UIResource)
 332             checkIcon = null;
 333     }
 334 
 335     /**
 336      * Unregisters components.
 337      *
 338      * @param menuItem a menu item
 339      * @since 1.3
 340      */
 341     protected void uninstallComponents(JMenuItem menuItem){
 342         BasicHTML.updateRenderer(menuItem, "");
 343     }
 344 
 345     /**
 346      * Unregisters listeners.
 347      */
 348     protected void uninstallListeners() {
 349         if (mouseInputListener != null) {
 350             menuItem.removeMouseListener(mouseInputListener);
 351             menuItem.removeMouseMotionListener(mouseInputListener);
 352         }
 353         if (menuDragMouseListener != null) {
 354             menuItem.removeMenuDragMouseListener(menuDragMouseListener);
 355         }
 356         if (menuKeyListener != null) {
 357             menuItem.removeMenuKeyListener(menuKeyListener);
 358         }
 359         if (propertyChangeListener != null) {
 360             menuItem.removePropertyChangeListener(propertyChangeListener);
 361         }
 362 
 363         mouseInputListener = null;
 364         menuDragMouseListener = null;
 365         menuKeyListener = null;
 366         propertyChangeListener = null;
 367         handler = null;
 368     }
 369 
 370     /**
 371      * Unregisters keyboard actions.
 372      */
 373     protected void uninstallKeyboardActions() {
 374         SwingUtilities.replaceUIActionMap(menuItem, null);
 375         SwingUtilities.replaceUIInputMap(menuItem, JComponent.
 376                                          WHEN_IN_FOCUSED_WINDOW, null);
 377     }
 378 
 379     /**
 380      * Returns an instance of {@code MouseInputListener}.
 381      *
 382      * @param c a component
 383      * @return an instance of {@code MouseInputListener}
 384      */
 385     protected MouseInputListener createMouseInputListener(JComponent c) {
 386         return getHandler();
 387     }
 388 
 389     /**
 390      * Returns an instance of {@code MenuDragMouseListener}.
 391      *
 392      * @param c a component
 393      * @return an instance of {@code MenuDragMouseListener}
 394      */
 395     protected MenuDragMouseListener createMenuDragMouseListener(JComponent c) {
 396         return getHandler();
 397     }
 398 
 399     /**
 400      * Returns an instance of {@code MenuKeyListener}.
 401      *
 402      * @param c a component
 403      * @return an instance of {@code MenuKeyListener}
 404      */
 405     protected MenuKeyListener createMenuKeyListener(JComponent c) {
 406         return null;
 407     }
 408 
 409     /**
 410      * Creates a {@code PropertyChangeListener} which will be added to
 411      * the menu item.
 412      * If this method returns null then it will not be added to the menu item.
 413      *
 414      * @param c a component
 415      * @return an instance of a {@code PropertyChangeListener} or null
 416      * @since 1.6
 417      */
 418     protected PropertyChangeListener
 419                                   createPropertyChangeListener(JComponent c) {
 420         return getHandler();
 421     }
 422 
 423     Handler getHandler() {
 424         if (handler == null) {
 425             handler = new Handler();
 426         }
 427         return handler;
 428     }
 429 
 430     InputMap createInputMap(int condition) {
 431         if (condition == JComponent.WHEN_IN_FOCUSED_WINDOW) {
 432             return new ComponentInputMapUIResource(menuItem);
 433         }
 434         return null;
 435     }
 436 
 437     void updateAcceleratorBinding() {
 438         KeyStroke accelerator = menuItem.getAccelerator();
 439         InputMap windowInputMap = SwingUtilities.getUIInputMap(
 440                        menuItem, JComponent.WHEN_IN_FOCUSED_WINDOW);
 441 
 442         if (windowInputMap != null) {
 443             windowInputMap.clear();
 444         }
 445         if (accelerator != null) {
 446             if (windowInputMap == null) {
 447                 windowInputMap = createInputMap(JComponent.
 448                                                 WHEN_IN_FOCUSED_WINDOW);
 449                 SwingUtilities.replaceUIInputMap(menuItem,
 450                            JComponent.WHEN_IN_FOCUSED_WINDOW, windowInputMap);
 451             }
 452             windowInputMap.put(accelerator, "doClick");
 453         }
 454     }
 455 
 456     public Dimension getMinimumSize(JComponent c) {
 457         Dimension d = null;
 458         View v = (View) c.getClientProperty(BasicHTML.propertyKey);
 459         if (v != null) {
 460             d = getPreferredSize(c);
 461             d.width -= v.getPreferredSpan(View.X_AXIS) - v.getMinimumSpan(View.X_AXIS);



 462         }

 463         return d;
 464     }
 465 
 466     public Dimension getPreferredSize(JComponent c) {
 467         return getPreferredMenuItemSize(c,
 468                                         checkIcon,
 469                                         arrowIcon,
 470                                         defaultTextIconGap);
 471     }
 472 
 473     public Dimension getMaximumSize(JComponent c) {
 474         Dimension d = null;
 475         View v = (View) c.getClientProperty(BasicHTML.propertyKey);
 476         if (v != null) {
 477             d = getPreferredSize(c);
 478             d.width += v.getMaximumSpan(View.X_AXIS) - v.getPreferredSpan(View.X_AXIS);
 479         }
 480         return d;
 481     }
 482 
 483     /**
 484      * Returns the preferred size of a menu item.
 485      *
 486      * @param c a component
 487      * @param checkIcon a check icon
 488      * @param arrowIcon an arrow icon
 489      * @param defaultTextIconGap a gap between a text and an icon
 490      * @return the preferred size of a menu item
 491      */
 492     protected Dimension getPreferredMenuItemSize(JComponent c,
 493                                                  Icon checkIcon,
 494                                                  Icon arrowIcon,
 495                                                  int defaultTextIconGap) {
 496 
 497         // The method also determines the preferred width of the
 498         // parent popup menu (through DefaultMenuLayout class).
 499         // The menu width equals to the maximal width
 500         // among child menu items.
 501 
 502         // Menu item width will be a sum of the widest check icon, label,
 503         // arrow icon and accelerator text among neighbor menu items.
 504         // For the latest menu item we will know the maximal widths exactly.
 505         // It will be the widest menu item and it will determine
 506         // the width of the parent popup menu.
 507 
 508         // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 509         // There is a conceptual problem: if user sets preferred size manually
 510         // for a menu item, this method won't be called for it
 511         // (see JComponent.getPreferredSize()),
 512         // maximal widths won't be calculated, other menu items won't be able
 513         // to take them into account and will be layouted in such a way,
 514         // as there is no the item with manual preferred size.
 515         // But after the first paint() method call, all maximal widths
 516         // will be correctly calculated and layout of some menu items
 517         // can be changed. For example, it can cause a shift of
 518         // the icon and text when user points a menu item by mouse.
 519 
 520         JMenuItem mi = (JMenuItem) c;
 521         MenuItemLayoutHelper lh = new MenuItemLayoutHelper(mi, checkIcon,
 522                 arrowIcon, MenuItemLayoutHelper.createMaxRect(), defaultTextIconGap,
 523                 acceleratorDelimiter, BasicGraphicsUtils.isLeftToRight(mi),
 524                 mi.getFont(), acceleratorFont,
 525                 MenuItemLayoutHelper.useCheckAndArrow(menuItem),
 526                 getPropertyPrefix());
 527 
 528         Dimension result = new Dimension();
 529 
 530         // Calculate the result width
 531         result.width = lh.getLeadingGap();
 532         MenuItemLayoutHelper.addMaxWidth(lh.getCheckSize(),
 533                 lh.getAfterCheckIconGap(), result);
 534         // Take into account mimimal text offset.
 535         if ((!lh.isTopLevelMenu())
 536                 && (lh.getMinTextOffset() > 0)
 537                 && (result.width < lh.getMinTextOffset())) {
 538             result.width = lh.getMinTextOffset();
 539         }
 540         MenuItemLayoutHelper.addMaxWidth(lh.getLabelSize(), lh.getGap(), result);
 541         MenuItemLayoutHelper.addMaxWidth(lh.getAccSize(), lh.getGap(), result);
 542         MenuItemLayoutHelper.addMaxWidth(lh.getArrowSize(), lh.getGap(), result);
 543 
 544         // Calculate the result height
 545         result.height = MenuItemLayoutHelper.max(lh.getCheckSize().getHeight(),
 546                 lh.getLabelSize().getHeight(), lh.getAccSize().getHeight(),
 547                 lh.getArrowSize().getHeight());
 548 
 549         // Take into account menu item insets
 550         Insets insets = lh.getMenuItem().getInsets();
 551         if(insets != null) {
 552             result.width += insets.left + insets.right;
 553             result.height += insets.top + insets.bottom;
 554         }
 555 
 556         // if the width is even, bump it up one. This is critical
 557         // for the focus dash line to draw properly
 558         if(result.width%2 == 0) {
 559             result.width++;
 560         }
 561 
 562         // if the height is even, bump it up one. This is critical
 563         // for the text to center properly
 564         if(result.height%2 == 0
 565                 && Boolean.TRUE !=
 566                     UIManager.get(getPropertyPrefix() + ".evenHeight")) {
 567             result.height++;
 568         }
 569 
 570         return result;
 571     }
 572 
 573     /**
 574      * We draw the background in paintMenuItem()
 575      * so override update (which fills the background of opaque
 576      * components by default) to just call paint().
 577      *
 578      */
 579     public void update(Graphics g, JComponent c) {
 580         paint(g, c);
 581     }
 582 
 583     public void paint(Graphics g, JComponent c) {
 584         paintMenuItem(g, c, checkIcon, arrowIcon,
 585                       selectionBackground, selectionForeground,
 586                       defaultTextIconGap);
 587     }
 588 
 589     /**
 590      * Paints a menu item.
 591      *
 592      * @param g an instance of {@code Graphics}
 593      * @param c a component
 594      * @param checkIcon a check icon
 595      * @param arrowIcon an arrow icon
 596      * @param background a background color
 597      * @param foreground a foreground color
 598      * @param defaultTextIconGap a gap between a text and an icon
 599      */
 600     protected void paintMenuItem(Graphics g, JComponent c,
 601                                      Icon checkIcon, Icon arrowIcon,
 602                                      Color background, Color foreground,
 603                                      int defaultTextIconGap) {
 604         // Save original graphics font and color
 605         Font holdf = g.getFont();
 606         Color holdc = g.getColor();
 607 
 608         JMenuItem mi = (JMenuItem) c;
 609         g.setFont(mi.getFont());
 610 
 611         Rectangle viewRect = new Rectangle(0, 0, mi.getWidth(), mi.getHeight());
 612         applyInsets(viewRect, mi.getInsets());
 613 
 614         MenuItemLayoutHelper lh = new MenuItemLayoutHelper(mi, checkIcon,
 615                 arrowIcon, viewRect, defaultTextIconGap, acceleratorDelimiter,
 616                 BasicGraphicsUtils.isLeftToRight(mi), mi.getFont(),
 617                 acceleratorFont, MenuItemLayoutHelper.useCheckAndArrow(menuItem),
 618                 getPropertyPrefix());
 619         MenuItemLayoutHelper.LayoutResult lr = lh.layoutMenuItem();
 620 
 621         paintBackground(g, mi, background);
 622         paintCheckIcon(g, lh, lr, holdc, foreground);
 623         paintIcon(g, lh, lr, holdc);
 624         paintText(g, lh, lr);
 625         paintAccText(g, lh, lr);
 626         paintArrowIcon(g, lh, lr, foreground);
 627 
 628         // Restore original graphics font and color
 629         g.setColor(holdc);
 630         g.setFont(holdf);
 631     }
 632 
 633     private void paintIcon(Graphics g, MenuItemLayoutHelper lh,
 634                            MenuItemLayoutHelper.LayoutResult lr, Color holdc) {
 635         if (lh.getIcon() != null) {
 636             Icon icon;
 637             ButtonModel model = lh.getMenuItem().getModel();
 638             if (!model.isEnabled()) {
 639                 icon = lh.getMenuItem().getDisabledIcon();
 640             } else if (model.isPressed() && model.isArmed()) {
 641                 icon = lh.getMenuItem().getPressedIcon();
 642                 if (icon == null) {
 643                     // Use default icon
 644                     icon = lh.getMenuItem().getIcon();
 645                 }
 646             } else {
 647                 icon = lh.getMenuItem().getIcon();
 648             }
 649 
 650             if (icon != null) {
 651                 icon.paintIcon(lh.getMenuItem(), g, lr.getIconRect().x,
 652                         lr.getIconRect().y);
 653                 g.setColor(holdc);
 654             }
 655         }
 656     }
 657 
 658     private void paintCheckIcon(Graphics g, MenuItemLayoutHelper lh,
 659                                 MenuItemLayoutHelper.LayoutResult lr,
 660                                 Color holdc, Color foreground) {
 661         if (lh.getCheckIcon() != null) {
 662             ButtonModel model = lh.getMenuItem().getModel();
 663             if (model.isArmed() || (lh.getMenuItem() instanceof JMenu
 664                     && model.isSelected())) {
 665                 g.setColor(foreground);
 666             } else {
 667                 g.setColor(holdc);
 668             }
 669             if (lh.useCheckAndArrow()) {
 670                 lh.getCheckIcon().paintIcon(lh.getMenuItem(), g,
 671                         lr.getCheckRect().x, lr.getCheckRect().y);
 672             }
 673             g.setColor(holdc);
 674         }
 675     }
 676 
 677     private void paintAccText(Graphics g, MenuItemLayoutHelper lh,
 678                               MenuItemLayoutHelper.LayoutResult lr) {
 679         if (!lh.getAccText().equals("")) {
 680             ButtonModel model = lh.getMenuItem().getModel();
 681             g.setFont(lh.getAccFontMetrics().getFont());
 682             if (!model.isEnabled()) {
 683                 // *** paint the accText disabled
 684                 if (disabledForeground != null) {
 685                     g.setColor(disabledForeground);
 686                     SwingUtilities2.drawString(lh.getMenuItem(), g,
 687                         lh.getAccText(), lr.getAccRect().x,
 688                         lr.getAccRect().y + lh.getAccFontMetrics().getAscent());
 689                 } else {
 690                     g.setColor(lh.getMenuItem().getBackground().brighter());
 691                     SwingUtilities2.drawString(lh.getMenuItem(), g,
 692                         lh.getAccText(), lr.getAccRect().x,
 693                         lr.getAccRect().y + lh.getAccFontMetrics().getAscent());
 694                     g.setColor(lh.getMenuItem().getBackground().darker());
 695                     SwingUtilities2.drawString(lh.getMenuItem(), g,
 696                         lh.getAccText(), lr.getAccRect().x - 1,
 697                         lr.getAccRect().y + lh.getFontMetrics().getAscent() - 1);
 698                 }
 699             } else {
 700                 // *** paint the accText normally
 701                 if (model.isArmed()
 702                         || (lh.getMenuItem() instanceof JMenu
 703                         && model.isSelected())) {
 704                     g.setColor(acceleratorSelectionForeground);
 705                 } else {
 706                     g.setColor(acceleratorForeground);
 707                 }
 708                 SwingUtilities2.drawString(lh.getMenuItem(), g, lh.getAccText(),
 709                         lr.getAccRect().x, lr.getAccRect().y +
 710                         lh.getAccFontMetrics().getAscent());
 711             }
 712         }
 713     }
 714 
 715     private void paintText(Graphics g, MenuItemLayoutHelper lh,
 716                            MenuItemLayoutHelper.LayoutResult lr) {
 717         if (!lh.getText().equals("")) {
 718             if (lh.getHtmlView() != null) {
 719                 // Text is HTML
 720                 lh.getHtmlView().paint(g, lr.getTextRect());
 721             } else {
 722                 // Text isn't HTML
 723                 paintText(g, lh.getMenuItem(), lr.getTextRect(), lh.getText());
 724             }
 725         }
 726     }
 727 
 728     private void paintArrowIcon(Graphics g, MenuItemLayoutHelper lh,
 729                                 MenuItemLayoutHelper.LayoutResult lr,
 730                                 Color foreground) {
 731         if (lh.getArrowIcon() != null) {
 732             ButtonModel model = lh.getMenuItem().getModel();
 733             if (model.isArmed() || (lh.getMenuItem() instanceof JMenu
 734                                 && model.isSelected())) {
 735                 g.setColor(foreground);
 736             }
 737             if (lh.useCheckAndArrow()) {
 738                 lh.getArrowIcon().paintIcon(lh.getMenuItem(), g,
 739                         lr.getArrowRect().x, lr.getArrowRect().y);
 740             }
 741         }
 742     }
 743 
 744     private void applyInsets(Rectangle rect, Insets insets) {
 745         if(insets != null) {
 746             rect.x += insets.left;
 747             rect.y += insets.top;
 748             rect.width -= (insets.right + rect.x);
 749             rect.height -= (insets.bottom + rect.y);
 750         }
 751     }
 752 
 753     /**
 754      * Draws the background of the menu item.
 755      *
 756      * @param g the paint graphics
 757      * @param menuItem menu item to be painted
 758      * @param bgColor selection background color
 759      * @since 1.4
 760      */
 761     protected void paintBackground(Graphics g, JMenuItem menuItem, Color bgColor) {
 762         ButtonModel model = menuItem.getModel();
 763         Color oldColor = g.getColor();
 764         int menuWidth = menuItem.getWidth();
 765         int menuHeight = menuItem.getHeight();
 766 
 767         if(menuItem.isOpaque()) {
 768             if (model.isArmed()|| (menuItem instanceof JMenu && model.isSelected())) {
 769                 g.setColor(bgColor);
 770                 g.fillRect(0,0, menuWidth, menuHeight);
 771             } else {
 772                 g.setColor(menuItem.getBackground());
 773                 g.fillRect(0,0, menuWidth, menuHeight);
 774             }
 775             g.setColor(oldColor);
 776         }
 777         else if (model.isArmed() || (menuItem instanceof JMenu &&
 778                                      model.isSelected())) {
 779             g.setColor(bgColor);
 780             g.fillRect(0,0, menuWidth, menuHeight);
 781             g.setColor(oldColor);
 782         }
 783     }
 784 
 785     /**
 786      * Renders the text of the current menu item.
 787      *
 788      * @param g graphics context
 789      * @param menuItem menu item to render
 790      * @param textRect bounding rectangle for rendering the text
 791      * @param text string to render
 792      * @since 1.4
 793      */
 794     protected void paintText(Graphics g, JMenuItem menuItem, Rectangle textRect, String text) {
 795         ButtonModel model = menuItem.getModel();
 796         FontMetrics fm = SwingUtilities2.getFontMetrics(menuItem, g);
 797         int mnemIndex = menuItem.getDisplayedMnemonicIndex();
 798 
 799         if(!model.isEnabled()) {
 800             // *** paint the text disabled
 801             if ( UIManager.get("MenuItem.disabledForeground") instanceof Color ) {
 802                 g.setColor( UIManager.getColor("MenuItem.disabledForeground") );
 803                 SwingUtilities2.drawStringUnderlineCharAt(menuItem, g,text,
 804                           mnemIndex, textRect.x,  textRect.y + fm.getAscent());
 805             } else {
 806                 g.setColor(menuItem.getBackground().brighter());
 807                 SwingUtilities2.drawStringUnderlineCharAt(menuItem, g, text,
 808                            mnemIndex, textRect.x, textRect.y + fm.getAscent());
 809                 g.setColor(menuItem.getBackground().darker());
 810                 SwingUtilities2.drawStringUnderlineCharAt(menuItem, g,text,
 811                            mnemIndex,  textRect.x - 1, textRect.y +
 812                            fm.getAscent() - 1);
 813             }
 814         } else {
 815             // *** paint the text normally
 816             if (model.isArmed()|| (menuItem instanceof JMenu && model.isSelected())) {
 817                 g.setColor(selectionForeground); // Uses protected field.
 818             }
 819             SwingUtilities2.drawStringUnderlineCharAt(menuItem, g,text,
 820                            mnemIndex, textRect.x, textRect.y + fm.getAscent());
 821         }
 822     }
 823 
 824     /**
 825      * Returns a menu element path.
 826      *
 827      * @return a menu element path
 828      */
 829     public MenuElement[] getPath() {
 830         MenuSelectionManager m = MenuSelectionManager.defaultManager();
 831         MenuElement oldPath[] = m.getSelectedPath();
 832         MenuElement newPath[];
 833         int i = oldPath.length;
 834         if (i == 0)
 835             return new MenuElement[0];
 836         Component parent = menuItem.getParent();
 837         if (oldPath[i-1].getComponent() == parent) {
 838             // The parent popup menu is the last so far
 839             newPath = new MenuElement[i+1];
 840             System.arraycopy(oldPath, 0, newPath, 0, i);
 841             newPath[i] = menuItem;
 842         } else {
 843             // A sibling menuitem is the current selection
 844             //
 845             //  This probably needs to handle 'exit submenu into
 846             // a menu item.  Search backwards along the current
 847             // selection until you find the parent popup menu,
 848             // then copy up to that and add yourself...
 849             int j;
 850             for (j = oldPath.length-1; j >= 0; j--) {
 851                 if (oldPath[j].getComponent() == parent)
 852                     break;
 853             }
 854             newPath = new MenuElement[j+2];
 855             System.arraycopy(oldPath, 0, newPath, 0, j+1);
 856             newPath[j+1] = menuItem;
 857             /*
 858             System.out.println("Sibling condition -- ");
 859             System.out.println("Old array : ");
 860             printMenuElementArray(oldPath, false);
 861             System.out.println("New array : ");
 862             printMenuElementArray(newPath, false);
 863             */
 864         }
 865         return newPath;
 866     }
 867 
 868     void printMenuElementArray(MenuElement path[], boolean dumpStack) {
 869         System.out.println("Path is(");
 870         int i, j;
 871         for(i=0,j=path.length; i<j ;i++){
 872             for (int k=0; k<=i; k++)
 873                 System.out.print("  ");
 874             MenuElement me = path[i];
 875             if(me instanceof JMenuItem)
 876                 System.out.println(((JMenuItem)me).getText() + ", ");
 877             else if (me == null)
 878                 System.out.println("NULL , ");
 879             else
 880                 System.out.println("" + me + ", ");
 881         }
 882         System.out.println(")");
 883 
 884         if (dumpStack == true)
 885             Thread.dumpStack();
 886     }
 887     /** Mouse input handler */
 888     protected class MouseInputHandler implements MouseInputListener {
 889         // NOTE: This class exists only for backward compatibility. All
 890         // its functionality has been moved into Handler. If you need to add
 891         // new functionality add it to the Handler, but make sure this
 892         // class calls into the Handler.
 893 
 894         /** {@inheritDoc} */
 895         public void mouseClicked(MouseEvent e) {
 896             getHandler().mouseClicked(e);
 897         }
 898         /** {@inheritDoc} */
 899         public void mousePressed(MouseEvent e) {
 900             getHandler().mousePressed(e);
 901         }
 902         /** {@inheritDoc} */
 903         public void mouseReleased(MouseEvent e) {
 904             getHandler().mouseReleased(e);
 905         }
 906         /** {@inheritDoc} */
 907         public void mouseEntered(MouseEvent e) {
 908             getHandler().mouseEntered(e);
 909         }
 910         /** {@inheritDoc} */
 911         public void mouseExited(MouseEvent e) {
 912             getHandler().mouseExited(e);
 913         }
 914         /** {@inheritDoc} */
 915         public void mouseDragged(MouseEvent e) {
 916             getHandler().mouseDragged(e);
 917         }
 918         /** {@inheritDoc} */
 919         public void mouseMoved(MouseEvent e) {
 920             getHandler().mouseMoved(e);
 921         }
 922     }
 923 
 924 
 925     private static class Actions extends UIAction {
 926         private static final String CLICK = "doClick";
 927 
 928         Actions(String key) {
 929             super(key);
 930         }
 931 
 932         public void actionPerformed(ActionEvent e) {
 933             JMenuItem mi = (JMenuItem)e.getSource();
 934             MenuSelectionManager.defaultManager().clearSelectedPath();
 935             mi.doClick();
 936         }
 937     }
 938 
 939     boolean doNotCloseOnMouseClick() {
 940         if (menuItem instanceof JCheckBoxMenuItem) {
 941             String property = "CheckBoxMenuItem.doNotCloseOnMouseClick";
 942             return SwingUtilities2.getBoolean(menuItem, property);
 943         } else if (menuItem instanceof JRadioButtonMenuItem) {
 944             String property = "RadioButtonMenuItem.doNotCloseOnMouseClick";
 945             return SwingUtilities2.getBoolean(menuItem, property);
 946         }
 947         return false;
 948     }
 949 
 950     /**
 951      * Call this method when a menu item is to be activated.
 952      * This method handles some of the details of menu item activation
 953      * such as clearing the selected path and messaging the
 954      * JMenuItem's doClick() method.
 955      *
 956      * @param msm  A MenuSelectionManager. The visual feedback and
 957      *             internal bookkeeping tasks are delegated to
 958      *             this MenuSelectionManager. If <code>null</code> is
 959      *             passed as this argument, the
 960      *             <code>MenuSelectionManager.defaultManager</code> is
 961      *             used.
 962      * @see MenuSelectionManager
 963      * @see JMenuItem#doClick(int)
 964      * @since 1.4
 965      */
 966     protected void doClick(MenuSelectionManager msm) {
 967         // Auditory cue
 968         if (! isInternalFrameSystemMenu()) {
 969             BasicLookAndFeel.playSound(menuItem, getPropertyPrefix() +
 970                                        ".commandSound");
 971         }
 972         if (!doNotCloseOnMouseClick()) {
 973             // Visual feedback
 974             if (msm == null) {
 975                 msm = MenuSelectionManager.defaultManager();
 976             }
 977 
 978             msm.clearSelectedPath();
 979         }
 980         menuItem.doClick(0);
 981     }
 982 
 983     /**
 984      * This is to see if the menu item in question is part of the
 985      * system menu on an internal frame.
 986      * The Strings that are being checked can be found in
 987      * MetalInternalFrameTitlePaneUI.java,
 988      * WindowsInternalFrameTitlePaneUI.java, and
 989      * MotifInternalFrameTitlePaneUI.java.
 990      *
 991      * @since 1.4
 992      */
 993     private boolean isInternalFrameSystemMenu() {
 994         String actionCommand = menuItem.getActionCommand();
 995         if ((actionCommand == "Close") ||
 996             (actionCommand == "Minimize") ||
 997             (actionCommand == "Restore") ||
 998             (actionCommand == "Maximize")) {
 999           return true;
1000         } else {
1001           return false;
1002         }
1003     }
1004 
1005 
1006     // BasicMenuUI subclasses this.
1007     class Handler implements MenuDragMouseListener,
1008                           MouseInputListener, PropertyChangeListener {
1009         //
1010         // MouseInputListener
1011         //
1012         public void mouseClicked(MouseEvent e) {}
1013         public void mousePressed(MouseEvent e) {
1014         }
1015         public void mouseReleased(MouseEvent e) {
1016             if (!menuItem.isEnabled()) {
1017                 return;
1018             }
1019             MenuSelectionManager manager =
1020                 MenuSelectionManager.defaultManager();
1021             Point p = e.getPoint();
1022             if(p.x >= 0 && p.x < menuItem.getWidth() &&
1023                p.y >= 0 && p.y < menuItem.getHeight()) {
1024                 doClick(manager);
1025             } else {
1026                 manager.processMouseEvent(e);
1027             }
1028         }
1029         @SuppressWarnings("deprecation")
1030         public void mouseEntered(MouseEvent e) {
1031             MenuSelectionManager manager = MenuSelectionManager.defaultManager();
1032             int modifiers = e.getModifiers();
1033             // 4188027: drag enter/exit added in JDK 1.1.7A, JDK1.2
1034             if ((modifiers & (InputEvent.BUTTON1_MASK |
1035                               InputEvent.BUTTON2_MASK | InputEvent.BUTTON3_MASK)) !=0 ) {
1036                 MenuSelectionManager.defaultManager().processMouseEvent(e);
1037             } else {
1038             manager.setSelectedPath(getPath());
1039              }
1040         }
1041         @SuppressWarnings("deprecation")
1042         public void mouseExited(MouseEvent e) {
1043             MenuSelectionManager manager = MenuSelectionManager.defaultManager();
1044 
1045             int modifiers = e.getModifiers();
1046             // 4188027: drag enter/exit added in JDK 1.1.7A, JDK1.2
1047             if ((modifiers & (InputEvent.BUTTON1_MASK |
1048                               InputEvent.BUTTON2_MASK | InputEvent.BUTTON3_MASK)) !=0 ) {
1049                 MenuSelectionManager.defaultManager().processMouseEvent(e);
1050             } else {
1051 
1052                 MenuElement path[] = manager.getSelectedPath();
1053                 if (path.length > 1 && path[path.length-1] == menuItem) {
1054                     MenuElement newPath[] = new MenuElement[path.length-1];
1055                     int i,c;
1056                     for(i=0,c=path.length-1;i<c;i++)
1057                         newPath[i] = path[i];
1058                     manager.setSelectedPath(newPath);
1059                 }
1060                 }
1061         }
1062 
1063         public void mouseDragged(MouseEvent e) {
1064             MenuSelectionManager.defaultManager().processMouseEvent(e);
1065         }
1066         public void mouseMoved(MouseEvent e) {
1067         }
1068 
1069         //
1070         // MenuDragListener
1071         //
1072         public void menuDragMouseEntered(MenuDragMouseEvent e) {
1073             MenuSelectionManager manager = e.getMenuSelectionManager();
1074             MenuElement path[] = e.getPath();
1075             manager.setSelectedPath(path);
1076         }
1077         public void menuDragMouseDragged(MenuDragMouseEvent e) {
1078             MenuSelectionManager manager = e.getMenuSelectionManager();
1079             MenuElement path[] = e.getPath();
1080             manager.setSelectedPath(path);
1081         }
1082         public void menuDragMouseExited(MenuDragMouseEvent e) {}
1083         public void menuDragMouseReleased(MenuDragMouseEvent e) {
1084             if (!menuItem.isEnabled()) {
1085                 return;
1086             }
1087             MenuSelectionManager manager = e.getMenuSelectionManager();
1088             MenuElement path[] = e.getPath();
1089             Point p = e.getPoint();
1090             if (p.x >= 0 && p.x < menuItem.getWidth() &&
1091                     p.y >= 0 && p.y < menuItem.getHeight()) {
1092                 doClick(manager);
1093             } else {
1094                 manager.clearSelectedPath();
1095             }
1096         }
1097 
1098 
1099         //
1100         // PropertyChangeListener
1101         //
1102         public void propertyChange(PropertyChangeEvent e) {
1103             String name = e.getPropertyName();
1104 
1105             if (name == "labelFor" || name == "displayedMnemonic" ||
1106                 name == "accelerator") {
1107                 updateAcceleratorBinding();
1108             } else if (name == "text" || "font" == name ||
1109                        "foreground" == name) {
1110                 // remove the old html view client property if one
1111                 // existed, and install a new one if the text installed
1112                 // into the JLabel is html source.
1113                 JMenuItem lbl = ((JMenuItem) e.getSource());
1114                 String text = lbl.getText();
1115                 BasicHTML.updateRenderer(lbl, text);
1116             } else if (name  == "iconTextGap") {
1117                 defaultTextIconGap = ((Number)e.getNewValue()).intValue();
1118             } else if (name == "horizontalTextPosition") {
1119                 updateCheckIcon();
1120             }
1121         }
1122     }
1123 }
--- EOF ---