1. /*
  2. * @(#)BasicMenuItemUI.java 1.128 03/12/19
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package javax.swing.plaf.basic;
  8. import com.sun.java.swing.SwingUtilities2;
  9. import java.awt.*;
  10. import java.awt.event.*;
  11. import java.beans.PropertyChangeEvent;
  12. import java.beans.PropertyChangeListener;
  13. import javax.swing.*;
  14. import javax.swing.event.*;
  15. import javax.swing.border.*;
  16. import javax.swing.plaf.*;
  17. import javax.swing.text.View;
  18. import sun.swing.UIAction;
  19. /**
  20. * BasicMenuItem implementation
  21. *
  22. * @version 1.128 12/19/03
  23. * @author Georges Saab
  24. * @author David Karlton
  25. * @author Arnaud Weber
  26. * @author Fredrik Lagerblad
  27. */
  28. public class BasicMenuItemUI extends MenuItemUI
  29. {
  30. protected JMenuItem menuItem = null;
  31. protected Color selectionBackground;
  32. protected Color selectionForeground;
  33. protected Color disabledForeground;
  34. protected Color acceleratorForeground;
  35. protected Color acceleratorSelectionForeground;
  36. private String acceleratorDelimiter;
  37. protected int defaultTextIconGap;
  38. protected Font acceleratorFont;
  39. protected MouseInputListener mouseInputListener;
  40. protected MenuDragMouseListener menuDragMouseListener;
  41. protected MenuKeyListener menuKeyListener;
  42. // BasicMenuUI also uses this.
  43. Handler handler;
  44. protected Icon arrowIcon = null;
  45. protected Icon checkIcon = null;
  46. protected boolean oldBorderPainted;
  47. /* diagnostic aids -- should be false for production builds. */
  48. private static final boolean TRACE = false; // trace creates and disposes
  49. private static final boolean VERBOSE = false; // show reuse hits/misses
  50. private static final boolean DEBUG = false; // show bad params, misc.
  51. /* Client Property keys for text and accelerator text widths */
  52. static final String MAX_TEXT_WIDTH = "maxTextWidth";
  53. static final String MAX_ACC_WIDTH = "maxAccWidth";
  54. static void loadActionMap(LazyActionMap map) {
  55. // NOTE: BasicMenuUI also calls into this method.
  56. map.put(new Actions(Actions.CLICK));
  57. BasicLookAndFeel.installAudioActionMap(map);
  58. }
  59. public static ComponentUI createUI(JComponent c) {
  60. return new BasicMenuItemUI();
  61. }
  62. public void installUI(JComponent c) {
  63. menuItem = (JMenuItem) c;
  64. installDefaults();
  65. installComponents(menuItem);
  66. installListeners();
  67. installKeyboardActions();
  68. }
  69. protected void installDefaults() {
  70. String prefix = getPropertyPrefix();
  71. acceleratorFont = UIManager.getFont("MenuItem.acceleratorFont");
  72. Object opaque = UIManager.get(getPropertyPrefix() + ".opaque");
  73. if (opaque != null) {
  74. LookAndFeel.installProperty(menuItem, "opaque", opaque);
  75. }
  76. else {
  77. LookAndFeel.installProperty(menuItem, "opaque", Boolean.TRUE);
  78. }
  79. if(menuItem.getMargin() == null ||
  80. (menuItem.getMargin() instanceof UIResource)) {
  81. menuItem.setMargin(UIManager.getInsets(prefix + ".margin"));
  82. }
  83. defaultTextIconGap = 4; // Should be from table
  84. LookAndFeel.installBorder(menuItem, prefix + ".border");
  85. oldBorderPainted = menuItem.isBorderPainted(); // not used anymore
  86. LookAndFeel.installProperty(menuItem, "borderPainted",
  87. UIManager.get(prefix + ".borderPainted"));
  88. LookAndFeel.installColorsAndFont(menuItem,
  89. prefix + ".background",
  90. prefix + ".foreground",
  91. prefix + ".font");
  92. // MenuItem specific defaults
  93. if (selectionBackground == null ||
  94. selectionBackground instanceof UIResource) {
  95. selectionBackground =
  96. UIManager.getColor(prefix + ".selectionBackground");
  97. }
  98. if (selectionForeground == null ||
  99. selectionForeground instanceof UIResource) {
  100. selectionForeground =
  101. UIManager.getColor(prefix + ".selectionForeground");
  102. }
  103. if (disabledForeground == null ||
  104. disabledForeground instanceof UIResource) {
  105. disabledForeground =
  106. UIManager.getColor(prefix + ".disabledForeground");
  107. }
  108. if (acceleratorForeground == null ||
  109. acceleratorForeground instanceof UIResource) {
  110. acceleratorForeground =
  111. UIManager.getColor(prefix + ".acceleratorForeground");
  112. }
  113. if (acceleratorSelectionForeground == null ||
  114. acceleratorSelectionForeground instanceof UIResource) {
  115. acceleratorSelectionForeground =
  116. UIManager.getColor(prefix + ".acceleratorSelectionForeground");
  117. }
  118. // Get accelerator delimiter
  119. acceleratorDelimiter =
  120. UIManager.getString("MenuItem.acceleratorDelimiter");
  121. if (acceleratorDelimiter == null) { acceleratorDelimiter = "+"; }
  122. // Icons
  123. if (arrowIcon == null ||
  124. arrowIcon instanceof UIResource) {
  125. arrowIcon = UIManager.getIcon(prefix + ".arrowIcon");
  126. }
  127. if (checkIcon == null ||
  128. checkIcon instanceof UIResource) {
  129. checkIcon = UIManager.getIcon(prefix + ".checkIcon");
  130. }
  131. }
  132. /**
  133. * @since 1.3
  134. */
  135. protected void installComponents(JMenuItem menuItem){
  136. BasicHTML.updateRenderer(menuItem, menuItem.getText());
  137. }
  138. protected String getPropertyPrefix() {
  139. return "MenuItem";
  140. }
  141. protected void installListeners() {
  142. if ((mouseInputListener = createMouseInputListener(menuItem)) != null) {
  143. menuItem.addMouseListener(mouseInputListener);
  144. menuItem.addMouseMotionListener(mouseInputListener);
  145. }
  146. if ((menuDragMouseListener = createMenuDragMouseListener(menuItem)) != null) {
  147. menuItem.addMenuDragMouseListener(menuDragMouseListener);
  148. }
  149. if ((menuKeyListener = createMenuKeyListener(menuItem)) != null) {
  150. menuItem.addMenuKeyListener(menuKeyListener);
  151. }
  152. menuItem.addPropertyChangeListener(getHandler());
  153. }
  154. protected void installKeyboardActions() {
  155. installLazyActionMap();
  156. updateAcceleratorBinding();
  157. }
  158. void installLazyActionMap() {
  159. LazyActionMap.installLazyActionMap(menuItem, BasicMenuItemUI.class,
  160. getPropertyPrefix() + ".actionMap");
  161. }
  162. public void uninstallUI(JComponent c) {
  163. menuItem = (JMenuItem)c;
  164. uninstallDefaults();
  165. uninstallComponents(menuItem);
  166. uninstallListeners();
  167. uninstallKeyboardActions();
  168. //Remove the textWidth and accWidth values from the parent's Client Properties.
  169. Container parent = menuItem.getParent();
  170. if ( (parent != null && parent instanceof JComponent) &&
  171. !(menuItem instanceof JMenu && ((JMenu) menuItem).isTopLevelMenu())) {
  172. JComponent p = (JComponent) parent;
  173. p.putClientProperty(BasicMenuItemUI.MAX_ACC_WIDTH, null );
  174. p.putClientProperty(BasicMenuItemUI.MAX_TEXT_WIDTH, null );
  175. }
  176. menuItem = null;
  177. }
  178. protected void uninstallDefaults() {
  179. LookAndFeel.uninstallBorder(menuItem);
  180. if (menuItem.getMargin() instanceof UIResource)
  181. menuItem.setMargin(null);
  182. if (arrowIcon instanceof UIResource)
  183. arrowIcon = null;
  184. if (checkIcon instanceof UIResource)
  185. checkIcon = null;
  186. }
  187. /**
  188. * @since 1.3
  189. */
  190. protected void uninstallComponents(JMenuItem menuItem){
  191. BasicHTML.updateRenderer(menuItem, "");
  192. }
  193. protected void uninstallListeners() {
  194. if (mouseInputListener != null) {
  195. menuItem.removeMouseListener(mouseInputListener);
  196. menuItem.removeMouseMotionListener(mouseInputListener);
  197. }
  198. if (menuDragMouseListener != null) {
  199. menuItem.removeMenuDragMouseListener(menuDragMouseListener);
  200. }
  201. if (menuKeyListener != null) {
  202. menuItem.removeMenuKeyListener(menuKeyListener);
  203. }
  204. menuItem.removePropertyChangeListener(getHandler());
  205. mouseInputListener = null;
  206. menuDragMouseListener = null;
  207. menuKeyListener = null;
  208. handler = null;
  209. }
  210. protected void uninstallKeyboardActions() {
  211. SwingUtilities.replaceUIActionMap(menuItem, null);
  212. SwingUtilities.replaceUIInputMap(menuItem, JComponent.
  213. WHEN_IN_FOCUSED_WINDOW, null);
  214. }
  215. protected MouseInputListener createMouseInputListener(JComponent c) {
  216. return getHandler();
  217. }
  218. protected MenuDragMouseListener createMenuDragMouseListener(JComponent c) {
  219. return getHandler();
  220. }
  221. protected MenuKeyListener createMenuKeyListener(JComponent c) {
  222. return null;
  223. }
  224. Handler getHandler() {
  225. if (handler == null) {
  226. handler = new Handler();
  227. }
  228. return handler;
  229. }
  230. InputMap createInputMap(int condition) {
  231. if (condition == JComponent.WHEN_IN_FOCUSED_WINDOW) {
  232. return new ComponentInputMapUIResource(menuItem);
  233. }
  234. return null;
  235. }
  236. void updateAcceleratorBinding() {
  237. KeyStroke accelerator = menuItem.getAccelerator();
  238. InputMap windowInputMap = SwingUtilities.getUIInputMap(
  239. menuItem, JComponent.WHEN_IN_FOCUSED_WINDOW);
  240. if (windowInputMap != null) {
  241. windowInputMap.clear();
  242. }
  243. if (accelerator != null) {
  244. if (windowInputMap == null) {
  245. windowInputMap = createInputMap(JComponent.
  246. WHEN_IN_FOCUSED_WINDOW);
  247. SwingUtilities.replaceUIInputMap(menuItem,
  248. JComponent.WHEN_IN_FOCUSED_WINDOW, windowInputMap);
  249. }
  250. windowInputMap.put(accelerator, "doClick");
  251. }
  252. }
  253. public Dimension getMinimumSize(JComponent c) {
  254. Dimension d = null;
  255. View v = (View) c.getClientProperty(BasicHTML.propertyKey);
  256. if (v != null) {
  257. d = getPreferredSize(c);
  258. d.width -= v.getPreferredSpan(View.X_AXIS) - v.getMinimumSpan(View.X_AXIS);
  259. }
  260. return d;
  261. }
  262. public Dimension getPreferredSize(JComponent c) {
  263. return getPreferredMenuItemSize(c,
  264. checkIcon,
  265. arrowIcon,
  266. defaultTextIconGap);
  267. }
  268. public Dimension getMaximumSize(JComponent c) {
  269. Dimension d = null;
  270. View v = (View) c.getClientProperty(BasicHTML.propertyKey);
  271. if (v != null) {
  272. d = getPreferredSize(c);
  273. d.width += v.getMaximumSpan(View.X_AXIS) - v.getPreferredSpan(View.X_AXIS);
  274. }
  275. return d;
  276. }
  277. // these rects are used for painting and preferredsize calculations.
  278. // they used to be regenerated constantly. Now they are reused.
  279. static Rectangle zeroRect = new Rectangle(0,0,0,0);
  280. static Rectangle iconRect = new Rectangle();
  281. static Rectangle textRect = new Rectangle();
  282. static Rectangle acceleratorRect = new Rectangle();
  283. static Rectangle checkIconRect = new Rectangle();
  284. static Rectangle arrowIconRect = new Rectangle();
  285. static Rectangle viewRect = new Rectangle(Short.MAX_VALUE, Short.MAX_VALUE);
  286. static Rectangle r = new Rectangle();
  287. private void resetRects() {
  288. iconRect.setBounds(zeroRect);
  289. textRect.setBounds(zeroRect);
  290. acceleratorRect.setBounds(zeroRect);
  291. checkIconRect.setBounds(zeroRect);
  292. arrowIconRect.setBounds(zeroRect);
  293. viewRect.setBounds(0,0,Short.MAX_VALUE, Short.MAX_VALUE);
  294. r.setBounds(zeroRect);
  295. }
  296. protected Dimension getPreferredMenuItemSize(JComponent c,
  297. Icon checkIcon,
  298. Icon arrowIcon,
  299. int defaultTextIconGap) {
  300. JMenuItem b = (JMenuItem) c;
  301. Icon icon = (Icon) b.getIcon();
  302. String text = b.getText();
  303. KeyStroke accelerator = b.getAccelerator();
  304. String acceleratorText = "";
  305. if (accelerator != null) {
  306. int modifiers = accelerator.getModifiers();
  307. if (modifiers > 0) {
  308. acceleratorText = KeyEvent.getKeyModifiersText(modifiers);
  309. //acceleratorText += "-";
  310. acceleratorText += acceleratorDelimiter;
  311. }
  312. int keyCode = accelerator.getKeyCode();
  313. if (keyCode != 0) {
  314. acceleratorText += KeyEvent.getKeyText(keyCode);
  315. } else {
  316. acceleratorText += accelerator.getKeyChar();
  317. }
  318. }
  319. Font font = b.getFont();
  320. FontMetrics fm = b.getFontMetrics(font);
  321. FontMetrics fmAccel = b.getFontMetrics( acceleratorFont );
  322. resetRects();
  323. layoutMenuItem(
  324. fm, text, fmAccel, acceleratorText, icon, checkIcon, arrowIcon,
  325. b.getVerticalAlignment(), b.getHorizontalAlignment(),
  326. b.getVerticalTextPosition(), b.getHorizontalTextPosition(),
  327. viewRect, iconRect, textRect, acceleratorRect, checkIconRect, arrowIconRect,
  328. text == null ? 0 : defaultTextIconGap,
  329. defaultTextIconGap
  330. );
  331. // find the union of the icon and text rects
  332. r.setBounds(textRect);
  333. r = SwingUtilities.computeUnion(iconRect.x,
  334. iconRect.y,
  335. iconRect.width,
  336. iconRect.height,
  337. r);
  338. // r = iconRect.union(textRect);
  339. // To make the accelerator texts appear in a column, find the widest MenuItem text
  340. // and the widest accelerator text.
  341. //Get the parent, which stores the information.
  342. Container parent = menuItem.getParent();
  343. //Check the parent, and see that it is not a top-level menu.
  344. if (parent != null && parent instanceof JComponent &&
  345. !(menuItem instanceof JMenu && ((JMenu) menuItem).isTopLevelMenu())) {
  346. JComponent p = (JComponent) parent;
  347. //Get widest text so far from parent, if no one exists null is returned.
  348. Integer maxTextWidth = (Integer) p.getClientProperty(BasicMenuItemUI.MAX_TEXT_WIDTH);
  349. Integer maxAccWidth = (Integer) p.getClientProperty(BasicMenuItemUI.MAX_ACC_WIDTH);
  350. int maxTextValue = maxTextWidth!=null ? maxTextWidth.intValue() : 0;
  351. int maxAccValue = maxAccWidth!=null ? maxAccWidth.intValue() : 0;
  352. //Compare the text widths, and adjust the r.width to the widest.
  353. if (r.width < maxTextValue) {
  354. r.width = maxTextValue;
  355. } else {
  356. p.putClientProperty(BasicMenuItemUI.MAX_TEXT_WIDTH, new Integer(r.width) );
  357. }
  358. //Compare the accelarator widths.
  359. if (acceleratorRect.width > maxAccValue) {
  360. maxAccValue = acceleratorRect.width;
  361. p.putClientProperty(BasicMenuItemUI.MAX_ACC_WIDTH, new Integer(acceleratorRect.width) );
  362. }
  363. //Add on the widest accelerator
  364. r.width += maxAccValue;
  365. r.width += defaultTextIconGap;
  366. }
  367. if( useCheckAndArrow() ) {
  368. // Add in the checkIcon
  369. r.width += checkIconRect.width;
  370. r.width += defaultTextIconGap;
  371. // Add in the arrowIcon
  372. r.width += defaultTextIconGap;
  373. r.width += arrowIconRect.width;
  374. }
  375. r.width += 2*defaultTextIconGap;
  376. Insets insets = b.getInsets();
  377. if(insets != null) {
  378. r.width += insets.left + insets.right;
  379. r.height += insets.top + insets.bottom;
  380. }
  381. // if the width is even, bump it up one. This is critical
  382. // for the focus dash line to draw properly
  383. if(r.width%2 == 0) {
  384. r.width++;
  385. }
  386. // if the height is even, bump it up one. This is critical
  387. // for the text to center properly
  388. if(r.height%2 == 0) {
  389. r.height++;
  390. }
  391. /*
  392. if(!(b instanceof JMenu && ((JMenu) b).isTopLevelMenu()) ) {
  393. // Container parent = menuItem.getParent();
  394. JComponent p = (JComponent) parent;
  395. System.out.println("MaxText: "+p.getClientProperty(BasicMenuItemUI.MAX_TEXT_WIDTH));
  396. System.out.println("MaxACC"+p.getClientProperty(BasicMenuItemUI.MAX_ACC_WIDTH));
  397. System.out.println("returning pref.width: " + r.width);
  398. System.out.println("Current getSize: " + b.getSize() + "\n");
  399. }*/
  400. return r.getSize();
  401. }
  402. /**
  403. * We draw the background in paintMenuItem()
  404. * so override update (which fills the background of opaque
  405. * components by default) to just call paint().
  406. *
  407. */
  408. public void update(Graphics g, JComponent c) {
  409. paint(g, c);
  410. }
  411. public void paint(Graphics g, JComponent c) {
  412. paintMenuItem(g, c, checkIcon, arrowIcon,
  413. selectionBackground, selectionForeground,
  414. defaultTextIconGap);
  415. }
  416. protected void paintMenuItem(Graphics g, JComponent c,
  417. Icon checkIcon, Icon arrowIcon,
  418. Color background, Color foreground,
  419. int defaultTextIconGap) {
  420. JMenuItem b = (JMenuItem) c;
  421. ButtonModel model = b.getModel();
  422. // Dimension size = b.getSize();
  423. int menuWidth = b.getWidth();
  424. int menuHeight = b.getHeight();
  425. Insets i = c.getInsets();
  426. resetRects();
  427. viewRect.setBounds( 0, 0, menuWidth, menuHeight );
  428. viewRect.x += i.left;
  429. viewRect.y += i.top;
  430. viewRect.width -= (i.right + viewRect.x);
  431. viewRect.height -= (i.bottom + viewRect.y);
  432. Font holdf = g.getFont();
  433. Font f = c.getFont();
  434. g.setFont( f );
  435. FontMetrics fm = SwingUtilities2.getFontMetrics(c, g, f);
  436. FontMetrics fmAccel = SwingUtilities2.getFontMetrics(
  437. c, g, acceleratorFont);
  438. // get Accelerator text
  439. KeyStroke accelerator = b.getAccelerator();
  440. String acceleratorText = "";
  441. if (accelerator != null) {
  442. int modifiers = accelerator.getModifiers();
  443. if (modifiers > 0) {
  444. acceleratorText = KeyEvent.getKeyModifiersText(modifiers);
  445. //acceleratorText += "-";
  446. acceleratorText += acceleratorDelimiter;
  447. }
  448. int keyCode = accelerator.getKeyCode();
  449. if (keyCode != 0) {
  450. acceleratorText += KeyEvent.getKeyText(keyCode);
  451. } else {
  452. acceleratorText += accelerator.getKeyChar();
  453. }
  454. }
  455. // layout the text and icon
  456. String text = layoutMenuItem(
  457. fm, b.getText(), fmAccel, acceleratorText, b.getIcon(),
  458. checkIcon, arrowIcon,
  459. b.getVerticalAlignment(), b.getHorizontalAlignment(),
  460. b.getVerticalTextPosition(), b.getHorizontalTextPosition(),
  461. viewRect, iconRect, textRect, acceleratorRect,
  462. checkIconRect, arrowIconRect,
  463. b.getText() == null ? 0 : defaultTextIconGap,
  464. defaultTextIconGap
  465. );
  466. // Paint background
  467. paintBackground(g, b, background);
  468. Color holdc = g.getColor();
  469. // Paint the Check
  470. if (checkIcon != null) {
  471. if(model.isArmed() || (c instanceof JMenu && model.isSelected())) {
  472. g.setColor(foreground);
  473. } else {
  474. g.setColor(holdc);
  475. }
  476. if( useCheckAndArrow() )
  477. checkIcon.paintIcon(c, g, checkIconRect.x, checkIconRect.y);
  478. g.setColor(holdc);
  479. }
  480. // Paint the Icon
  481. if(b.getIcon() != null) {
  482. Icon icon;
  483. if(!model.isEnabled()) {
  484. icon = (Icon) b.getDisabledIcon();
  485. } else if(model.isPressed() && model.isArmed()) {
  486. icon = (Icon) b.getPressedIcon();
  487. if(icon == null) {
  488. // Use default icon
  489. icon = (Icon) b.getIcon();
  490. }
  491. } else {
  492. icon = (Icon) b.getIcon();
  493. }
  494. if (icon!=null)
  495. icon.paintIcon(c, g, iconRect.x, iconRect.y);
  496. }
  497. // Draw the Text
  498. if(text != null) {
  499. View v = (View) c.getClientProperty(BasicHTML.propertyKey);
  500. if (v != null) {
  501. v.paint(g, textRect);
  502. } else {
  503. paintText(g, b, textRect, text);
  504. }
  505. }
  506. // Draw the Accelerator Text
  507. if(acceleratorText != null && !acceleratorText.equals("")) {
  508. //Get the maxAccWidth from the parent to calculate the offset.
  509. int accOffset = 0;
  510. Container parent = menuItem.getParent();
  511. if (parent != null && parent instanceof JComponent) {
  512. JComponent p = (JComponent) parent;
  513. Integer maxValueInt = (Integer) p.getClientProperty(BasicMenuItemUI.MAX_ACC_WIDTH);
  514. int maxValue = maxValueInt != null ?
  515. maxValueInt.intValue() : acceleratorRect.width;
  516. //Calculate the offset, with which the accelerator texts will be drawn with.
  517. accOffset = maxValue - acceleratorRect.width;
  518. }
  519. g.setFont( acceleratorFont );
  520. if(!model.isEnabled()) {
  521. // *** paint the acceleratorText disabled
  522. if ( disabledForeground != null )
  523. {
  524. g.setColor( disabledForeground );
  525. SwingUtilities2.drawString(b, g,acceleratorText,
  526. acceleratorRect.x - accOffset,
  527. acceleratorRect.y + fmAccel.getAscent());
  528. }
  529. else
  530. {
  531. g.setColor(b.getBackground().brighter());
  532. SwingUtilities2.drawString(b, g,acceleratorText,
  533. acceleratorRect.x - accOffset,
  534. acceleratorRect.y + fmAccel.getAscent());
  535. g.setColor(b.getBackground().darker());
  536. SwingUtilities2.drawString(b, g,acceleratorText,
  537. acceleratorRect.x - accOffset - 1,
  538. acceleratorRect.y + fmAccel.getAscent() - 1);
  539. }
  540. } else {
  541. // *** paint the acceleratorText normally
  542. if (model.isArmed()|| (c instanceof JMenu && model.isSelected())) {
  543. g.setColor( acceleratorSelectionForeground );
  544. } else {
  545. g.setColor( acceleratorForeground );
  546. }
  547. SwingUtilities2.drawString(b, g,acceleratorText,
  548. acceleratorRect.x - accOffset,
  549. acceleratorRect.y + fmAccel.getAscent());
  550. }
  551. }
  552. // Paint the Arrow
  553. if (arrowIcon != null) {
  554. if(model.isArmed() || (c instanceof JMenu &&model.isSelected()))
  555. g.setColor(foreground);
  556. if(useCheckAndArrow())
  557. arrowIcon.paintIcon(c, g, arrowIconRect.x, arrowIconRect.y);
  558. }
  559. g.setColor(holdc);
  560. g.setFont(holdf);
  561. }
  562. /**
  563. * Draws the background of the menu item.
  564. *
  565. * @param g the paint graphics
  566. * @param menuItem menu item to be painted
  567. * @param bgColor selection background color
  568. * @since 1.4
  569. */
  570. protected void paintBackground(Graphics g, JMenuItem menuItem, Color bgColor) {
  571. ButtonModel model = menuItem.getModel();
  572. Color oldColor = g.getColor();
  573. int menuWidth = menuItem.getWidth();
  574. int menuHeight = menuItem.getHeight();
  575. if(menuItem.isOpaque()) {
  576. if (model.isArmed()|| (menuItem instanceof JMenu && model.isSelected())) {
  577. g.setColor(bgColor);
  578. g.fillRect(0,0, menuWidth, menuHeight);
  579. } else {
  580. g.setColor(menuItem.getBackground());
  581. g.fillRect(0,0, menuWidth, menuHeight);
  582. }
  583. g.setColor(oldColor);
  584. }
  585. else if (model.isArmed() || (menuItem instanceof JMenu &&
  586. model.isSelected())) {
  587. g.setColor(bgColor);
  588. g.fillRect(0,0, menuWidth, menuHeight);
  589. g.setColor(oldColor);
  590. }
  591. }
  592. /**
  593. * Renders the text of the current menu item.
  594. * <p>
  595. * @param g graphics context
  596. * @param menuItem menu item to render
  597. * @param textRect bounding rectangle for rendering the text
  598. * @param text string to render
  599. * @since 1.4
  600. */
  601. protected void paintText(Graphics g, JMenuItem menuItem, Rectangle textRect, String text) {
  602. ButtonModel model = menuItem.getModel();
  603. FontMetrics fm = SwingUtilities2.getFontMetrics(menuItem, g);
  604. int mnemIndex = menuItem.getDisplayedMnemonicIndex();
  605. if(!model.isEnabled()) {
  606. // *** paint the text disabled
  607. if ( UIManager.get("MenuItem.disabledForeground") instanceof Color ) {
  608. g.setColor( UIManager.getColor("MenuItem.disabledForeground") );
  609. SwingUtilities2.drawStringUnderlineCharAt(menuItem, g,text,
  610. mnemIndex, textRect.x, textRect.y + fm.getAscent());
  611. } else {
  612. g.setColor(menuItem.getBackground().brighter());
  613. SwingUtilities2.drawStringUnderlineCharAt(menuItem, g, text,
  614. mnemIndex, textRect.x, textRect.y + fm.getAscent());
  615. g.setColor(menuItem.getBackground().darker());
  616. SwingUtilities2.drawStringUnderlineCharAt(menuItem, g,text,
  617. mnemIndex, textRect.x - 1, textRect.y +
  618. fm.getAscent() - 1);
  619. }
  620. } else {
  621. // *** paint the text normally
  622. if (model.isArmed()|| (menuItem instanceof JMenu && model.isSelected())) {
  623. g.setColor(selectionForeground); // Uses protected field.
  624. }
  625. SwingUtilities2.drawStringUnderlineCharAt(menuItem, g,text,
  626. mnemIndex, textRect.x, textRect.y + fm.getAscent());
  627. }
  628. }
  629. /**
  630. * Compute and return the location of the icons origin, the
  631. * location of origin of the text baseline, and a possibly clipped
  632. * version of the compound labels string. Locations are computed
  633. * relative to the viewRect rectangle.
  634. */
  635. private String layoutMenuItem(
  636. FontMetrics fm,
  637. String text,
  638. FontMetrics fmAccel,
  639. String acceleratorText,
  640. Icon icon,
  641. Icon checkIcon,
  642. Icon arrowIcon,
  643. int verticalAlignment,
  644. int horizontalAlignment,
  645. int verticalTextPosition,
  646. int horizontalTextPosition,
  647. Rectangle viewRect,
  648. Rectangle iconRect,
  649. Rectangle textRect,
  650. Rectangle acceleratorRect,
  651. Rectangle checkIconRect,
  652. Rectangle arrowIconRect,
  653. int textIconGap,
  654. int menuItemGap
  655. )
  656. {
  657. SwingUtilities.layoutCompoundLabel(
  658. menuItem, fm, text, icon, verticalAlignment,
  659. horizontalAlignment, verticalTextPosition,
  660. horizontalTextPosition, viewRect, iconRect, textRect,
  661. textIconGap);
  662. /* Initialize the acceelratorText bounds rectangle textRect. If a null
  663. * or and empty String was specified we substitute "" here
  664. * and use 0,0,0,0 for acceleratorTextRect.
  665. */
  666. if( (acceleratorText == null) || acceleratorText.equals("") ) {
  667. acceleratorRect.width = acceleratorRect.height = 0;
  668. acceleratorText = "";
  669. }
  670. else {
  671. acceleratorRect.width = SwingUtilities2.stringWidth(
  672. menuItem, fmAccel, acceleratorText);
  673. acceleratorRect.height = fmAccel.getHeight();
  674. }
  675. /* Initialize the checkIcon bounds rectangle's width & height.
  676. */
  677. if( useCheckAndArrow()) {
  678. if (checkIcon != null) {
  679. checkIconRect.width = checkIcon.getIconWidth();
  680. checkIconRect.height = checkIcon.getIconHeight();
  681. }
  682. else {
  683. checkIconRect.width = checkIconRect.height = 0;
  684. }
  685. /* Initialize the arrowIcon bounds rectangle width & height.
  686. */
  687. if (arrowIcon != null) {
  688. arrowIconRect.width = arrowIcon.getIconWidth();
  689. arrowIconRect.height = arrowIcon.getIconHeight();
  690. } else {
  691. arrowIconRect.width = arrowIconRect.height = 0;
  692. }
  693. }
  694. Rectangle labelRect = iconRect.union(textRect);
  695. if( BasicGraphicsUtils.isLeftToRight(menuItem) ) {
  696. textRect.x += menuItemGap;
  697. iconRect.x += menuItemGap;
  698. // Position the Accelerator text rect
  699. acceleratorRect.x = viewRect.x + viewRect.width - arrowIconRect.width
  700. - menuItemGap - acceleratorRect.width;
  701. // Position the Check and Arrow Icons
  702. if (useCheckAndArrow()) {
  703. checkIconRect.x = viewRect.x + menuItemGap;
  704. textRect.x += menuItemGap + checkIconRect.width;
  705. iconRect.x += menuItemGap + checkIconRect.width;
  706. arrowIconRect.x = viewRect.x + viewRect.width - menuItemGap
  707. - arrowIconRect.width;
  708. }
  709. } else {
  710. textRect.x -= menuItemGap;
  711. iconRect.x -= menuItemGap;
  712. // Position the Accelerator text rect
  713. acceleratorRect.x = viewRect.x + arrowIconRect.width + menuItemGap;
  714. // Position the Check and Arrow Icons
  715. if (useCheckAndArrow()) {
  716. checkIconRect.x = viewRect.x + viewRect.width - menuItemGap
  717. - checkIconRect.width;
  718. textRect.x -= menuItemGap + checkIconRect.width;
  719. iconRect.x -= menuItemGap + checkIconRect.width;
  720. arrowIconRect.x = viewRect.x + menuItemGap;
  721. }
  722. }
  723. // Align the accelertor text and the check and arrow icons vertically
  724. // with the center of the label rect.
  725. acceleratorRect.y = labelRect.y + (labelRect.height2) - (acceleratorRect.height2);
  726. if( useCheckAndArrow() ) {
  727. arrowIconRect.y = labelRect.y + (labelRect.height2) - (arrowIconRect.height2);
  728. checkIconRect.y = labelRect.y + (labelRect.height2) - (checkIconRect.height2);
  729. }
  730. /*
  731. System.out.println("Layout: text="+menuItem.getText()+"\n\tv="
  732. +viewRect+"\n\tc="+checkIconRect+"\n\ti="
  733. +iconRect+"\n\tt="+textRect+"\n\tacc="
  734. +acceleratorRect+"\n\ta="+arrowIconRect+"\n");
  735. */
  736. return text;
  737. }
  738. /*
  739. * Returns false if the component is a JMenu and it is a top
  740. * level menu (on the menubar).
  741. */
  742. private boolean useCheckAndArrow(){
  743. boolean b = true;
  744. if((menuItem instanceof JMenu) &&
  745. (((JMenu)menuItem).isTopLevelMenu())) {
  746. b = false;
  747. }
  748. return b;
  749. }
  750. public MenuElement[] getPath() {
  751. MenuSelectionManager m = MenuSelectionManager.defaultManager();
  752. MenuElement oldPath[] = m.getSelectedPath();
  753. MenuElement newPath[];
  754. int i = oldPath.length;
  755. if (i == 0)
  756. return new MenuElement[0];
  757. Component parent = menuItem.getParent();
  758. if (oldPath[i-1].getComponent() == parent) {
  759. // The parent popup menu is the last so far
  760. newPath = new MenuElement[i+1];
  761. System.arraycopy(oldPath, 0, newPath, 0, i);
  762. newPath[i] = menuItem;
  763. } else {
  764. // A sibling menuitem is the current selection
  765. //
  766. // This probably needs to handle 'exit submenu into
  767. // a menu item. Search backwards along the current
  768. // selection until you find the parent popup menu,
  769. // then copy up to that and add yourself...
  770. int j;
  771. for (j = oldPath.length-1; j >= 0; j--) {
  772. if (oldPath[j].getComponent() == parent)
  773. break;
  774. }
  775. newPath = new MenuElement[j+2];
  776. System.arraycopy(oldPath, 0, newPath, 0, j+1);
  777. newPath[j+1] = menuItem;
  778. /*
  779. System.out.println("Sibling condition -- ");
  780. System.out.println("Old array : ");
  781. printMenuElementArray(oldPath, false);
  782. System.out.println("New array : ");
  783. printMenuElementArray(newPath, false);
  784. */
  785. }
  786. return newPath;
  787. }
  788. void printMenuElementArray(MenuElement path[], boolean dumpStack) {
  789. System.out.println("Path is(");
  790. int i, j;
  791. for(i=0,j=path.length; i<j ;i++){
  792. for (int k=0; k<=i; k++)
  793. System.out.print(" ");
  794. MenuElement me = (MenuElement) path[i];
  795. if(me instanceof JMenuItem)
  796. System.out.println(((JMenuItem)me).getText() + ", ");
  797. else if (me == null)
  798. System.out.println("NULL , ");
  799. else
  800. System.out.println("" + me + ", ");
  801. }
  802. System.out.println(")");
  803. if (dumpStack == true)
  804. Thread.dumpStack();
  805. }
  806. protected class MouseInputHandler implements MouseInputListener {
  807. // NOTE: This class exists only for backward compatability. All
  808. // its functionality has been moved into Handler. If you need to add
  809. // new functionality add it to the Handler, but make sure this
  810. // class calls into the Handler.
  811. public void mouseClicked(MouseEvent e) {
  812. getHandler().mouseClicked(e);
  813. }
  814. public void mousePressed(MouseEvent e) {
  815. getHandler().mousePressed(e);
  816. }
  817. public void mouseReleased(MouseEvent e) {
  818. getHandler().mouseReleased(e);
  819. }
  820. public void mouseEntered(MouseEvent e) {
  821. getHandler().mouseEntered(e);
  822. }
  823. public void mouseExited(MouseEvent e) {
  824. getHandler().mouseExited(e);
  825. }
  826. public void mouseDragged(MouseEvent e) {
  827. getHandler().mouseDragged(e);
  828. }
  829. public void mouseMoved(MouseEvent e) {
  830. getHandler().mouseMoved(e);
  831. }
  832. }
  833. private static class Actions extends UIAction {
  834. private static final String CLICK = "doClick";
  835. Actions(String key) {
  836. super(key);
  837. }
  838. public void actionPerformed(ActionEvent e) {
  839. JMenuItem mi = (JMenuItem)e.getSource();
  840. MenuSelectionManager.defaultManager().clearSelectedPath();
  841. mi.doClick();
  842. }
  843. }
  844. /**
  845. * Call this method when a menu item is to be activated.
  846. * This method handles some of the details of menu item activation
  847. * such as clearing the selected path and messaging the
  848. * JMenuItem's doClick() method.
  849. *
  850. * @param msm A MenuSelectionManager. The visual feedback and
  851. * internal bookkeeping tasks are delegated to
  852. * this MenuSelectionManager. If <code>null</code> is
  853. * passed as this argument, the
  854. * <code>MenuSelectionManager.defaultManager</code> is
  855. * used.
  856. * @see MenuSelectionManager
  857. * @see JMenuItem#doClick(int)
  858. * @since 1.4
  859. */
  860. protected void doClick(MenuSelectionManager msm) {
  861. // Auditory cue
  862. if (! isInternalFrameSystemMenu()) {
  863. BasicLookAndFeel.playSound(menuItem, getPropertyPrefix() +
  864. ".commandSound");
  865. }
  866. // Visual feedback
  867. if (msm == null) {
  868. msm = MenuSelectionManager.defaultManager();
  869. }
  870. msm.clearSelectedPath();
  871. menuItem.doClick(0);
  872. }
  873. /**
  874. * This is to see if the menu item in question is part of the
  875. * system menu on an internal frame.
  876. * The Strings that are being checked can be found in
  877. * MetalInternalFrameTitlePaneUI.java,
  878. * WindowsInternalFrameTitlePaneUI.java, and
  879. * MotifInternalFrameTitlePaneUI.java.
  880. *
  881. * @since 1.4
  882. */
  883. private boolean isInternalFrameSystemMenu() {
  884. String actionCommand = menuItem.getActionCommand();
  885. if ((actionCommand == "Close") ||
  886. (actionCommand == "Minimize") ||
  887. (actionCommand == "Restore") ||
  888. (actionCommand == "Maximize")) {
  889. return true;
  890. } else {
  891. return false;
  892. }
  893. }
  894. // BasicMenuUI subclasses this.
  895. class Handler implements MenuDragMouseListener,
  896. MouseInputListener, PropertyChangeListener {
  897. //
  898. // MouseInputListener
  899. //
  900. public void mouseClicked(MouseEvent e) {}
  901. public void mousePressed(MouseEvent e) {
  902. }
  903. public void mouseReleased(MouseEvent e) {
  904. MenuSelectionManager manager =
  905. MenuSelectionManager.defaultManager();
  906. Point p = e.getPoint();
  907. if(p.x >= 0 && p.x < menuItem.getWidth() &&
  908. p.y >= 0 && p.y < menuItem.getHeight()) {
  909. doClick(manager);
  910. } else {
  911. manager.processMouseEvent(e);
  912. }
  913. }
  914. public void mouseEntered(MouseEvent e) {
  915. MenuSelectionManager manager = MenuSelectionManager.defaultManager();
  916. int modifiers = e.getModifiers();
  917. // 4188027: drag enter/exit added in JDK 1.1.7A, JDK1.2
  918. if ((modifiers & (InputEvent.BUTTON1_MASK |
  919. InputEvent.BUTTON2_MASK | InputEvent.BUTTON3_MASK)) !=0 ) {
  920. MenuSelectionManager.defaultManager().processMouseEvent(e);
  921. } else {
  922. manager.setSelectedPath(getPath());
  923. }
  924. }
  925. public void mouseExited(MouseEvent e) {
  926. MenuSelectionManager manager = MenuSelectionManager.defaultManager();
  927. int modifiers = e.getModifiers();
  928. // 4188027: drag enter/exit added in JDK 1.1.7A, JDK1.2
  929. if ((modifiers & (InputEvent.BUTTON1_MASK |
  930. InputEvent.BUTTON2_MASK | InputEvent.BUTTON3_MASK)) !=0 ) {
  931. MenuSelectionManager.defaultManager().processMouseEvent(e);
  932. } else {
  933. MenuElement path[] = manager.getSelectedPath();
  934. if (path.length > 1 && path[path.length-1] == menuItem) {
  935. MenuElement newPath[] = new MenuElement[path.length-1];
  936. int i,c;
  937. for(i=0,c=path.length-1;i<c;i++)
  938. newPath[i] = path[i];
  939. manager.setSelectedPath(newPath);
  940. }
  941. }
  942. }
  943. public void mouseDragged(MouseEvent e) {
  944. MenuSelectionManager.defaultManager().processMouseEvent(e);
  945. }
  946. public void mouseMoved(MouseEvent e) {
  947. }
  948. //
  949. // MenuDragListener
  950. //
  951. public void menuDragMouseEntered(MenuDragMouseEvent e) {
  952. MenuSelectionManager manager = e.getMenuSelectionManager();
  953. MenuElement path[] = e.getPath();
  954. manager.setSelectedPath(path);
  955. }
  956. public void menuDragMouseDragged(MenuDragMouseEvent e) {
  957. MenuSelectionManager manager = e.getMenuSelectionManager();
  958. MenuElement path[] = e.getPath();
  959. manager.setSelectedPath(path);
  960. }
  961. public void menuDragMouseExited(MenuDragMouseEvent e) {}
  962. public void menuDragMouseReleased(MenuDragMouseEvent e) {
  963. MenuSelectionManager manager = e.getMenuSelectionManager();
  964. MenuElement path[] = e.getPath();
  965. Point p = e.getPoint();
  966. if(p.x >= 0 && p.x < menuItem.getWidth() &&
  967. p.y >= 0 && p.y < menuItem.getHeight()) {
  968. doClick(manager);
  969. } else {
  970. manager.clearSelectedPath();
  971. }
  972. }
  973. //
  974. // PropertyChangeListener
  975. //
  976. public void propertyChange(PropertyChangeEvent e) {
  977. String name = e.getPropertyName();
  978. if (name == "labelFor" || name == "displayedMnemonic" ||
  979. name == "accelerator") {
  980. updateAcceleratorBinding();
  981. } else if (name == "text" || "font" == name ||
  982. "foreground" == name) {
  983. // remove the old html view client property if one
  984. // existed, and install a new one if the text installed
  985. // into the JLabel is html source.
  986. JMenuItem lbl = ((JMenuItem) e.getSource());
  987. String text = lbl.getText();
  988. BasicHTML.updateRenderer(lbl, text);
  989. }
  990. }
  991. }
  992. }