1. /*
  2. * @(#)JMenuBar.java 1.85 00/04/06
  3. *
  4. * Copyright 1997-2000 Sun Microsystems, Inc. All Rights Reserved.
  5. *
  6. * This software is the proprietary information of Sun Microsystems, Inc.
  7. * Use is subject to license terms.
  8. *
  9. */
  10. package javax.swing;
  11. import java.awt.Component;
  12. import java.awt.Dimension;
  13. import java.awt.Graphics;
  14. import java.awt.Insets;
  15. import java.awt.Point;
  16. import java.awt.Rectangle;
  17. import java.awt.event.*;
  18. import java.util.Vector;
  19. import java.util.Enumeration;
  20. import java.io.Serializable;
  21. import java.io.ObjectOutputStream;
  22. import java.io.ObjectInputStream;
  23. import java.io.IOException;
  24. import javax.swing.event.*;
  25. import javax.swing.border.Border;
  26. import javax.swing.plaf.*;
  27. import javax.accessibility.*;
  28. /**
  29. * An implementation of a menu bar. You add <code>JMenu</code> objects to the
  30. * menu bar to construct a menu. When the user selects a <code>JMenu</code>
  31. * object, its associated <code>JPopupMenu</code> is displayed, allowing the
  32. * user to select one of the <code>JMenuItems</code> on it.
  33. * <p>
  34. * For information and examples of using menu bars see
  35. * <a
  36. href="http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html">How to Use Menus</a>,
  37. * a section in <em>The Java Tutorial.</em>
  38. * For the keyboard keys used by this component in the standard Look and
  39. * Feel (L&F) renditions, see the
  40. * <a href="doc-files/Key-Index.html#JMenuBar">JMenuBar</a> key assignments.
  41. * <p>
  42. * <strong>Warning:</strong>
  43. * Serialized objects of this class will not be compatible with
  44. * future Swing releases. The current serialization support is appropriate
  45. * for short term storage or RMI between applications running the same
  46. * version of Swing. A future release of Swing will provide support for
  47. * long term persistence.
  48. *
  49. * @beaninfo
  50. * attribute: isContainer true
  51. * description: A container for holding and displaying menus.
  52. *
  53. * @version 1.85 04/06/00
  54. * @author Georges Saab
  55. * @author David Karlton
  56. * @author Arnaud Weber
  57. * @see JMenu
  58. * @see JPopupMenu
  59. * @see JMenuItem
  60. */
  61. public class JMenuBar extends JComponent implements Accessible,MenuElement
  62. {
  63. /**
  64. * @see #getUIClassID
  65. * @see #readObject
  66. */
  67. private static final String uiClassID = "MenuBarUI";
  68. /*
  69. * Model for the selected subcontrol.
  70. */
  71. private transient SingleSelectionModel selectionModel;
  72. private boolean paintBorder = true;
  73. private Insets margin = null;
  74. /* diagnostic aids -- should be false for production builds. */
  75. private static final boolean TRACE = false; // trace creates and disposes
  76. private static final boolean VERBOSE = false; // show reuse hits/misses
  77. private static final boolean DEBUG = false; // show bad params, misc.
  78. /**
  79. * Creates a new menu bar.
  80. */
  81. public JMenuBar() {
  82. super();
  83. setSelectionModel(new DefaultSingleSelectionModel());
  84. updateUI();
  85. }
  86. /**
  87. * Returns the menubar's current UI.
  88. * @see #setUI
  89. */
  90. public MenuBarUI getUI() {
  91. return (MenuBarUI)ui;
  92. }
  93. /**
  94. * Sets the L&F object that renders this component.
  95. *
  96. * @param ui the new MenuBarUI L&F object
  97. * @see UIDefaults#getUI
  98. */
  99. public void setUI(MenuBarUI ui) {
  100. super.setUI(ui);
  101. }
  102. /**
  103. * Notification from the <code>UIFactory</code> that the L&F has changed.
  104. * Called to replace the UI with the latest version from the
  105. * <code>UIFactory</code>.
  106. *
  107. * @see JComponent#updateUI
  108. */
  109. public void updateUI() {
  110. setUI((MenuBarUI)UIManager.getUI(this));
  111. }
  112. /**
  113. * Returns the name of the L&F class that renders this component.
  114. *
  115. * @return the string "MenuBarUI"
  116. * @see JComponent#getUIClassID
  117. * @see UIDefaults#getUI
  118. */
  119. public String getUIClassID() {
  120. return uiClassID;
  121. }
  122. /**
  123. * Returns the model object that handles single selections.
  124. *
  125. * @return the <code>SingleSelectionModel</code> property
  126. * @see SingleSelectionModel
  127. */
  128. public SingleSelectionModel getSelectionModel() {
  129. return selectionModel;
  130. }
  131. /**
  132. * Sets the model object to handle single selections.
  133. *
  134. * @param model the <code>SingleSelectionModel</code> to use
  135. * @see SingleSelectionModel
  136. * @beaninfo
  137. * bound: true
  138. * description: The selection model, recording which child is selected.
  139. */
  140. public void setSelectionModel(SingleSelectionModel model) {
  141. SingleSelectionModel oldValue = selectionModel;
  142. this.selectionModel = model;
  143. firePropertyChange("selectionModel", oldValue, selectionModel);
  144. }
  145. /**
  146. * Appends the specified menu to the end of the menu bar.
  147. *
  148. * @param c the <code>JMenu</code> component to add
  149. * @return the menu component
  150. */
  151. public JMenu add(JMenu c) {
  152. super.add(c);
  153. return c;
  154. }
  155. /**
  156. * Returns the menu at the specified position in the menu bar.
  157. *
  158. * @param index an integer giving the position in the menu bar, where
  159. * 0 is the first position
  160. * @return the <code>JMenu</code> at that position, or <code>null</code> if
  161. * if there is no <code>JMenu</code> at that position (ie. if
  162. * it is a <code>JMenuItem</code>)
  163. */
  164. public JMenu getMenu(int index) {
  165. Component c = getComponentAtIndex(index);
  166. if (c instanceof JMenu)
  167. return (JMenu) c;
  168. return null;
  169. }
  170. /**
  171. * Returns the number of items in the menu bar.
  172. *
  173. * @return the number of items in the menu bar
  174. */
  175. public int getMenuCount() {
  176. return getComponentCount();
  177. }
  178. /**
  179. * Sets the help menu that appears when the user selects the
  180. * "help" option in the menu bar. This method is not yet implemented
  181. * and will throw an exception.
  182. *
  183. * @param menu the JMenu that delivers help to the user
  184. */
  185. public void setHelpMenu(JMenu menu) {
  186. throw new Error("setHelpMenu() not yet implemented.");
  187. }
  188. /**
  189. * Gets the help menu for the menu bar. This method is not yet
  190. * implemented and will throw an exception.
  191. *
  192. * @return the <code>JMenu</code> that delivers help to the user
  193. */
  194. public JMenu getHelpMenu() {
  195. throw new Error("getHelpMenu() not yet implemented.");
  196. }
  197. /**
  198. * Returns the component at the specified index.
  199. *
  200. * @param i an integer specifying the position, where 0 is first
  201. * @return the <code>Component</code> at the position,
  202. * or <code>null</code> for an invalid index
  203. * @deprecated replaced by <code>getComponent(int i)</code>
  204. */
  205. public Component getComponentAtIndex(int i) {
  206. return getComponent(i);
  207. }
  208. /**
  209. * Returns the index of the specified component.
  210. *
  211. * @param c the <code>Component</code> to find
  212. * @return an integer giving the component's position, where 0 is first;
  213. * or -1 if it can't be found
  214. */
  215. public int getComponentIndex(Component c) {
  216. int ncomponents = this.getComponentCount();
  217. Component[] component = this.getComponents();
  218. for (int i = 0 ; i < ncomponents ; i++) {
  219. Component comp = component[i];
  220. if (comp == c)
  221. return i;
  222. }
  223. return -1;
  224. }
  225. /**
  226. * Sets the currently selected component, producing a
  227. * a change to the selection model.
  228. *
  229. * @param sel the <code>Component</code> to select
  230. */
  231. public void setSelected(Component sel) {
  232. SingleSelectionModel model = getSelectionModel();
  233. int index = getComponentIndex(sel);
  234. model.setSelectedIndex(index);
  235. }
  236. /**
  237. * Returns true if the menu bar currently has a component selected.
  238. *
  239. * @return true if a selection has been made, else false
  240. */
  241. public boolean isSelected() {
  242. return selectionModel.isSelected();
  243. }
  244. /**
  245. * Returns true if the menu bars border should be painted.
  246. *
  247. * @return true if the border should be painted, else false
  248. */
  249. public boolean isBorderPainted() {
  250. return paintBorder;
  251. }
  252. /**
  253. * Sets whether the border should be painted.
  254. *
  255. * @param b if true and border property is not <code>null</code>,
  256. * the border is painted.
  257. * @see #isBorderPainted
  258. * @beaninfo
  259. * bound: true
  260. * attribute: visualUpdate true
  261. * description: Whether the border should be painted.
  262. */
  263. public void setBorderPainted(boolean b) {
  264. boolean oldValue = paintBorder;
  265. paintBorder = b;
  266. firePropertyChange("borderPainted", oldValue, paintBorder);
  267. if (b != oldValue) {
  268. revalidate();
  269. repaint();
  270. }
  271. }
  272. /**
  273. * Paints the menubar's border if <code>BorderPainted</code>
  274. * property is true.
  275. *
  276. * @param g the <code>Graphics</code> context to use for painting
  277. * @see JComponent#paint
  278. * @see JComponent#setBorder
  279. */
  280. protected void paintBorder(Graphics g) {
  281. if (isBorderPainted()) {
  282. super.paintBorder(g);
  283. }
  284. }
  285. /**
  286. * Sets the margin between the menubar's border and
  287. * its menus. Setting to <code>null</code> will cause the menubar to
  288. * use the default margins.
  289. *
  290. * @param margin an Insets object containing the margin values
  291. * @see Insets
  292. * @beaninfo
  293. * bound: true
  294. * attribute: visualUpdate true
  295. * description: The space between the menubar's border and its contents
  296. */
  297. public void setMargin(Insets m) {
  298. Insets old = margin;
  299. this.margin = m;
  300. firePropertyChange("margin", old, m);
  301. if (old == null || !m.equals(old)) {
  302. revalidate();
  303. repaint();
  304. }
  305. }
  306. /**
  307. * Returns the margin between the menubar's border and
  308. * its menus. If there is no previous margin, it will create
  309. * a default margin with zero size.
  310. *
  311. * @return an <code>Insets</code> object containing the margin values
  312. * @see Insets
  313. */
  314. public Insets getMargin() {
  315. if(margin == null) {
  316. return new Insets(0,0,0,0);
  317. } else {
  318. return margin;
  319. }
  320. }
  321. /**
  322. * Implemented to be a <code>MenuElement</code> -- does nothing.
  323. *
  324. * @see #getSubElements
  325. */
  326. public void processMouseEvent(MouseEvent event,MenuElement path[],MenuSelectionManager manager) {
  327. }
  328. /**
  329. * Implemented to be a <code>MenuElement</code> -- does nothing.
  330. *
  331. * @see #getSubElements
  332. */
  333. public void processKeyEvent(KeyEvent e,MenuElement path[],MenuSelectionManager manager) {
  334. }
  335. /**
  336. * Implemented to be a <code>MenuElemen<code>t -- does nothing.
  337. *
  338. * @see #getSubElements
  339. */
  340. public void menuSelectionChanged(boolean isIncluded) {
  341. }
  342. /**
  343. * Implemented to be a <code>MenuElement</code> -- returns the
  344. * menus in this menu bar.
  345. * This is the reason for implementing the <code>MenuElement</code>
  346. * interface -- so that the menu bar can be treated the same as
  347. * other menu elements.
  348. * @return an array of menu items in the menu bar.
  349. */
  350. public MenuElement[] getSubElements() {
  351. MenuElement result[];
  352. Vector tmp = new Vector();
  353. int c = getComponentCount();
  354. int i;
  355. Component m;
  356. for(i=0 ; i < c ; i++) {
  357. m = getComponent(i);
  358. if(m instanceof MenuElement)
  359. tmp.addElement(m);
  360. }
  361. result = new MenuElement[tmp.size()];
  362. for(i=0,c=tmp.size() ; i < c ; i++)
  363. result[i] = (MenuElement) tmp.elementAt(i);
  364. return result;
  365. }
  366. /**
  367. * Implemented to be a <code>MenuElement</code>. Returns this object.
  368. *
  369. * @return the current <code>Component</code> (this)
  370. * @see #getSubElements
  371. */
  372. public Component getComponent() {
  373. return this;
  374. }
  375. /**
  376. * Returns a string representation of this <code>JMenuBar</code>.
  377. * This method
  378. * is intended to be used only for debugging purposes, and the
  379. * content and format of the returned string may vary between
  380. * implementations. The returned string may be empty but may not
  381. * be <code>null</code>.
  382. *
  383. * @return a string representation of this <code>JMenuBar</code>
  384. */
  385. protected String paramString() {
  386. String paintBorderString = (paintBorder ?
  387. "true" : "false");
  388. String marginString = (margin != null ?
  389. margin.toString() : "");
  390. return super.paramString() +
  391. ",margin=" + marginString +
  392. ",paintBorder=" + paintBorderString;
  393. }
  394. /////////////////
  395. // Accessibility support
  396. ////////////////
  397. /**
  398. * Gets the AccessibleContext associated with this JMenuBar.
  399. * For JMenuBars, the AccessibleContext takes the form of an
  400. * AccessibleJMenuBar.
  401. * A new AccessibleJMenuBar instance is created if necessary.
  402. *
  403. * @return an AccessibleJMenuBar that serves as the
  404. * AccessibleContext of this JMenuBar
  405. */
  406. public AccessibleContext getAccessibleContext() {
  407. if (accessibleContext == null) {
  408. accessibleContext = new AccessibleJMenuBar();
  409. }
  410. return accessibleContext;
  411. }
  412. /**
  413. * This class implements accessibility support for the
  414. * <code>JMenuBar</code> class. It provides an implementation of the
  415. * Java Accessibility API appropriate to menu bar user-interface
  416. * elements.
  417. * <p>
  418. * <strong>Warning:</strong>
  419. * Serialized objects of this class will not be compatible with
  420. * future Swing releases. The current serialization support is appropriate
  421. * for short term storage or RMI between applications running the same
  422. * version of Swing. A future release of Swing will provide support for
  423. * long term persistence.
  424. */
  425. protected class AccessibleJMenuBar extends AccessibleJComponent
  426. implements AccessibleSelection {
  427. /**
  428. * Get the accessible state set of this object.
  429. *
  430. * @return an instance of AccessibleState containing the current state
  431. * of the object
  432. */
  433. public AccessibleStateSet getAccessibleStateSet() {
  434. AccessibleStateSet states = super.getAccessibleStateSet();
  435. return states;
  436. }
  437. /**
  438. * Get the role of this object.
  439. *
  440. * @return an instance of AccessibleRole describing the role of the
  441. * object
  442. */
  443. public AccessibleRole getAccessibleRole() {
  444. return AccessibleRole.MENU_BAR;
  445. }
  446. /**
  447. * Get the AccessibleSelection associated with this object. In the
  448. * implementation of the Java Accessibility API for this class,
  449. * return this object, which is responsible for implementing the
  450. * AccessibleSelection interface on behalf of itself.
  451. *
  452. * @return this object
  453. */
  454. public AccessibleSelection getAccessibleSelection() {
  455. return this;
  456. }
  457. /**
  458. * Returns 1 if a menu is currently selected in this menu bar.
  459. *
  460. * @return 1 if a menu is currently selected, else 0
  461. */
  462. public int getAccessibleSelectionCount() {
  463. if (isSelected()) {
  464. return 1;
  465. } else {
  466. return 0;
  467. }
  468. }
  469. /**
  470. * Returns the currently selected menu if one is selected,
  471. * otherwise null.
  472. */
  473. public Accessible getAccessibleSelection(int i) {
  474. if (isSelected()) {
  475. if (i != 0) { // single selection model for JMenuBar
  476. return null;
  477. }
  478. int j = getSelectionModel().getSelectedIndex();
  479. if (getComponentAtIndex(j) instanceof Accessible) {
  480. return (Accessible) getComponentAtIndex(j);
  481. }
  482. }
  483. return null;
  484. }
  485. /**
  486. * Returns true if the current child of this object is selected.
  487. *
  488. * @param i the zero-based index of the child in this Accessible
  489. * object.
  490. * @see AccessibleContext#getAccessibleChild
  491. */
  492. public boolean isAccessibleChildSelected(int i) {
  493. return (i == getSelectionModel().getSelectedIndex());
  494. }
  495. /**
  496. * Selects the nth menu in the menu bar, forcing it to
  497. * pop up. If another menu is popped up, this will force
  498. * it to close. If the nth menu is already selected, this
  499. * method has no effect.
  500. *
  501. * @param i the zero-based index of selectable items
  502. * @see #getAccessibleStateSet
  503. */
  504. public void addAccessibleSelection(int i) {
  505. // first close up any open menu
  506. int j = getSelectionModel().getSelectedIndex();
  507. if (i == j) {
  508. return;
  509. }
  510. if (j >= 0 && j < getMenuCount()) {
  511. JMenu menu = getMenu(j);
  512. if (menu != null) {
  513. MenuSelectionManager.defaultManager().setSelectedPath(null);
  514. // menu.setPopupMenuVisible(false);
  515. }
  516. }
  517. // now popup the new menu
  518. getSelectionModel().setSelectedIndex(i);
  519. JMenu menu = getMenu(i);
  520. if (menu != null) {
  521. MenuElement me[] = new MenuElement[3];
  522. me[0] = JMenuBar.this;
  523. me[1] = menu;
  524. me[2] = menu.getPopupMenu();
  525. MenuSelectionManager.defaultManager().setSelectedPath(me);
  526. // menu.setPopupMenuVisible(true);
  527. }
  528. }
  529. /**
  530. * Removes the nth selected item in the object from the object's
  531. * selection. If the nth item isn't currently selected, this
  532. * method has no effect. Otherwise, it closes the popup menu.
  533. *
  534. * @param i the zero-based index of selectable items
  535. */
  536. public void removeAccessibleSelection(int i) {
  537. if (i >= 0 && i < getMenuCount()) {
  538. JMenu menu = getMenu(i);
  539. if (menu != null) {
  540. MenuSelectionManager.defaultManager().setSelectedPath(null);
  541. // menu.setPopupMenuVisible(false);
  542. }
  543. getSelectionModel().setSelectedIndex(-1);
  544. }
  545. }
  546. /**
  547. * Clears the selection in the object, so that nothing in the
  548. * object is selected. This will close any open menu.
  549. */
  550. public void clearAccessibleSelection() {
  551. int i = getSelectionModel().getSelectedIndex();
  552. if (i >= 0 && i < getMenuCount()) {
  553. JMenu menu = getMenu(i);
  554. if (menu != null) {
  555. MenuSelectionManager.defaultManager().setSelectedPath(null);
  556. // menu.setPopupMenuVisible(false);
  557. }
  558. }
  559. getSelectionModel().setSelectedIndex(-1);
  560. }
  561. /**
  562. * Normally causes every selected item in the object to be selected
  563. * if the object supports multiple selections. This method
  564. * makes no sense in a menu bar, and so does nothing.
  565. */
  566. public void selectAllAccessibleSelection() {
  567. }
  568. } // internal class AccessibleJMenuBar
  569. /**
  570. * Returns true to indicate that this component manages focus
  571. * events internally.
  572. *
  573. * @return true
  574. */
  575. public boolean isManagingFocus() {
  576. return true;
  577. }
  578. /**
  579. * Subclassed to check all the child menus.
  580. */
  581. protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,
  582. int condition, boolean pressed) {
  583. // See if we have a local binding.
  584. boolean retValue = super.processKeyBinding(ks, e, condition, pressed);
  585. if (!retValue) {
  586. // We don't, pass along to children JMenu's
  587. Component subComponents[] = getComponents();
  588. for(int i=0 ; i < subComponents.length ; i++) {
  589. if ((subComponents[i] instanceof JMenu) &&
  590. processBindingForKeyStrokeRecursive
  591. ((JComponent)subComponents[i], ks, e, condition,
  592. pressed)) {
  593. return true;
  594. }
  595. }
  596. }
  597. return retValue;
  598. }
  599. static boolean processBindingForKeyStrokeRecursive(JComponent c,
  600. KeyStroke ks, KeyEvent e, int condition,
  601. boolean pressed) {
  602. if (c==null)
  603. return false;
  604. // Check the receiver.
  605. if (c.processKeyBinding(ks, e, condition, pressed)) {
  606. return true;
  607. }
  608. // Then, if the receiver is a JMenu, check the menuitems.
  609. if (c instanceof JMenu) {
  610. JMenu m = (JMenu)c;
  611. Component subComponents[];
  612. subComponents = m.getMenuComponents();
  613. if (subComponents != null) {
  614. for(int i=0 ; i < subComponents.length ; i++) {
  615. if ((subComponents[i] instanceof JMenuItem) &&
  616. processBindingForKeyStrokeRecursive
  617. ((JComponent)subComponents[i], ks, e, condition,
  618. pressed)) {
  619. return true;
  620. }
  621. }
  622. }
  623. }
  624. return false;
  625. }
  626. /**
  627. * Overrides <code>JComponent.addNotify</code> to register this
  628. * menu bar with the current keyboard manager.
  629. */
  630. public void addNotify() {
  631. super.addNotify();
  632. KeyboardManager.getCurrentManager().registerMenuBar(this);
  633. }
  634. /**
  635. * Overrides <code>JComponent.removeNotify</code> to unregister this
  636. * menu bar with the current keyboard manager.
  637. */
  638. public void removeNotify() {
  639. super.removeNotify();
  640. KeyboardManager.getCurrentManager().unregisterMenuBar(this);
  641. }
  642. private void writeObject(ObjectOutputStream s) throws IOException {
  643. s.defaultWriteObject();
  644. Object[] kvData = new Object[4];
  645. int n = 0;
  646. if (selectionModel instanceof Serializable) {
  647. kvData[n++] = "selectionModel";
  648. kvData[n++] = selectionModel;
  649. }
  650. s.writeObject(kvData);
  651. }
  652. /**
  653. * See JComponent.readObject() for information about serialization
  654. * in Swing.
  655. */
  656. private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException
  657. {
  658. s.defaultReadObject();
  659. Object[] kvData = (Object[])(s.readObject());
  660. for(int i = 0; i < kvData.length; i += 2) {
  661. if (kvData[i] == null) {
  662. break;
  663. }
  664. else if (kvData[i].equals("selectionModel")) {
  665. selectionModel = (SingleSelectionModel)kvData[i + 1];
  666. }
  667. }
  668. if ((ui != null) && (getUIClassID().equals(uiClassID))) {
  669. ui.installUI(this);
  670. }
  671. }
  672. }