Imported GNU Classpath 0.90
[official-gcc.git] / libjava / classpath / javax / swing / JPopupMenu.java
bloba54bd777fd4eaf63665fd9fc64032b12aaadeb98
1 /* JPopupMenu.java --
2 Copyright (C) 2002, 2004, 2005 Free Software Foundation, Inc.
4 This file is part of GNU Classpath.
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; see the file COPYING. If not, write to the
18 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 02110-1301 USA.
21 Linking this library statically or dynamically with other modules is
22 making a combined work based on this library. Thus, the terms and
23 conditions of the GNU General Public License cover the whole
24 combination.
26 As a special exception, the copyright holders of this library give you
27 permission to link this library with independent modules to produce an
28 executable, regardless of the license terms of these independent
29 modules, and to copy and distribute the resulting executable under
30 terms of your choice, provided that you also meet, for each linked
31 independent module, the terms and conditions of the license of that
32 module. An independent module is a module which is not derived from
33 or based on this library. If you modify this library, you may extend
34 this exception to your version of the library, but you are not
35 obligated to do so. If you do not wish to do so, delete this
36 exception statement from your version. */
39 package javax.swing;
41 import java.awt.Component;
42 import java.awt.Dimension;
43 import java.awt.Insets;
44 import java.awt.Point;
45 import java.awt.event.KeyEvent;
46 import java.awt.event.MouseEvent;
47 import java.beans.PropertyChangeEvent;
48 import java.beans.PropertyChangeListener;
49 import java.util.ArrayList;
50 import java.util.EventListener;
52 import javax.accessibility.Accessible;
53 import javax.accessibility.AccessibleContext;
54 import javax.accessibility.AccessibleRole;
55 import javax.swing.event.PopupMenuEvent;
56 import javax.swing.event.PopupMenuListener;
57 import javax.swing.plaf.PopupMenuUI;
59 /**
60 * JPopupMenu is a container that is used to display popup menu's menu
61 * items. By default JPopupMenu is a lightweight container, however if it
62 * is the case that JPopupMenu's bounds are outside of main window, then
63 * heawyweight container will be used to display menu items. It is also
64 * possible to change JPopupMenu's default behavior and set JPopupMenu
65 * to always use heavyweight container.
67 * JPopupMenu can be displayed anywhere; it is a floating free popup menu.
68 * However before JPopupMenu is diplayed, its invoker property should be set.
69 * JPopupMenu's invoker is a component relative to which popup menu is
70 * displayed.
72 * JPopupMenu fires PopupMenuEvents to its registered listeners. Whenever
73 * JPopupMenu becomes visible on the screen then PopupMenuEvent indicating
74 * that popup menu became visible will be fired. In the case when
75 * JPopupMenu becomes invisible or cancelled without selection, then
76 * popupMenuBecomeInvisible() or popupMenuCancelled() methods of
77 * PopupMenuListeners will be invoked.
79 * JPopupMenu also fires PropertyChangeEvents when its bound properties
80 * change.In addittion to inheritted bound properties, JPopupMenu has
81 * 'visible' bound property. When JPopupMenu becomes visible/invisible on
82 * the screen it fires PropertyChangeEvents to its registered
83 * PropertyChangeListeners.
85 public class JPopupMenu extends JComponent implements Accessible, MenuElement
87 private static final long serialVersionUID = -8336996630009646009L;
89 /* indicates if popup's menu border should be painted*/
90 private boolean borderPainted = true;
92 /** Flag indicating whether lightweight, mediumweight or heavyweight popup
93 is used to display menu items.
95 These are the possible cases:
97 1. if DefaultLightWeightPopupEnabled true
98 (i) use lightweight container if popup feets inside top-level window
99 (ii) only use heavyweight container (JDialog) if popup doesn't fit.
101 2. if DefaultLightWeightPopupEnabled false
102 (i) if popup fits, use awt.Panel (mediumWeight)
103 (ii) if popup doesn't fit, use JDialog (heavyWeight)
105 private static boolean DefaultLightWeightPopupEnabled = true;
107 /* Component that invokes popup menu. */
108 transient Component invoker;
110 /* Label for this popup menu. It is not used in most of the look and feel themes. */
111 private String label;
113 /*Amount of space between menuItem's in JPopupMenu and JPopupMenu's border */
114 private Insets margin;
116 /** Indicates whether ligthWeight container can be used to display popup
117 menu. This flag is the same as DefaultLightWeightPopupEnabled, but setting
118 this flag can change popup menu after creation of the object */
119 private boolean lightWeightPopupEnabled;
121 /** SelectionModel that keeps track of menu selection. */
122 private SingleSelectionModel selectionModel;
124 /* Popup that is used to display JPopupMenu */
125 private transient Popup popup;
128 * Location of the popup, X coordinate.
130 private int popupLocationX;
133 * Location of the popup, Y coordinate.
135 private int popupLocationY;
137 /* Field indicating if popup menu is visible or not */
138 private boolean visible = false;
141 * Creates a new JPopupMenu object.
143 public JPopupMenu()
145 this(null);
149 * Creates a new JPopupMenu with specified label
151 * @param label Label for popup menu.
153 public JPopupMenu(String label)
155 lightWeightPopupEnabled = getDefaultLightWeightPopupEnabled();
156 setLabel(label);
157 setSelectionModel(new DefaultSingleSelectionModel());
158 super.setVisible(false);
159 updateUI();
163 * Adds given menu item to the popup menu
165 * @param item menu item to add to the popup menu
167 * @return menu item that was added to the popup menu
169 public JMenuItem add(JMenuItem item)
171 this.insert(item, -1);
172 return item;
176 * Constructs menu item with a specified label and adds it to
177 * popup menu
179 * @param text label for the menu item to be added
181 * @return constructed menu item that was added to the popup menu
183 public JMenuItem add(String text)
185 JMenuItem item = new JMenuItem(text);
186 return add(item);
190 * Constructs menu item associated with the specified action
191 * and adds it to the popup menu
193 * @param action Action for the new menu item
195 * @return menu item that was added to the menu
197 public JMenuItem add(Action action)
199 JMenuItem item = createActionComponent(action);
201 if (action != null)
202 action.addPropertyChangeListener(createActionChangeListener(item));
204 return add(item);
208 * Revomes component at the given index from the menu.
210 * @param index index of the component that will be removed in the menu
212 public void remove(int index)
214 super.remove(index);
215 revalidate();
219 * Create menu item associated with the given action
220 * and inserts it into the popup menu at the specified index
222 * @param action Action for the new menu item
223 * @param index index in the popup menu at which to insert new menu item.
225 public void insert(Action action, int index)
227 JMenuItem item = new JMenuItem(action);
228 this.insert(item, index);
232 * Insert given component to the popup menu at the
233 * specified index
235 * @param component Component to insert
236 * @param index Index at which to insert given component
238 public void insert(Component component, int index)
240 super.add(component, index);
244 * Returns flag indicating if newly created JPopupMenu will use
245 * heavyweight or lightweight container to display its menu items
247 * @return true if JPopupMenu will use lightweight container to display
248 * menu items by default, and false otherwise.
250 public static boolean getDefaultLightWeightPopupEnabled()
252 return DefaultLightWeightPopupEnabled;
256 * Sets whether JPopupMenu should use ligthWeight container to
257 * display it menu items by default
259 * @param enabled true if JPopupMenu should use lightweight container
260 * for displaying its menu items, and false otherwise.
262 public static void setDefaultLightWeightPopupEnabled(boolean enabled)
264 DefaultLightWeightPopupEnabled = enabled;
268 * This method returns the UI used to display the JPopupMenu.
270 * @return The UI used to display the JPopupMenu.
272 public PopupMenuUI getUI()
274 return (PopupMenuUI) ui;
278 * Set the "UI" property of the menu item, which is a look and feel class
279 * responsible for handling popupMenu's input events and painting it.
281 * @param ui The new "UI" property
283 public void setUI(PopupMenuUI ui)
285 super.setUI(ui);
289 * This method sets this menuItem's UI to the UIManager's default for the
290 * current look and feel.
292 public void updateUI()
294 setUI((PopupMenuUI) UIManager.getUI(this));
298 * This method returns a name to identify which look and feel class will be
299 * the UI delegate for the menuItem.
301 * @return The Look and Feel classID. "PopupMenuUI"
303 public String getUIClassID()
305 return "PopupMenuUI";
309 * Returns selectionModel used by this popup menu to keep
310 * track of the selection.
312 * @return popup menu's selection model
314 public SingleSelectionModel getSelectionModel()
316 return selectionModel;
320 * Sets selection model for this popup menu
322 * @param model new selection model of this popup menu
324 public void setSelectionModel(SingleSelectionModel model)
326 selectionModel = model;
330 * Creates new menu item associated with a given action.
332 * @param action Action used to create new menu item
334 * @return new created menu item associated with a given action.
336 protected JMenuItem createActionComponent(Action action)
338 return new JMenuItem(action);
342 * Creates PropertyChangeListener that listens to PropertyChangeEvents
343 * occuring in the Action associated with given menu item in this popup menu.
345 * @param item MenuItem
347 * @return The PropertyChangeListener
349 protected PropertyChangeListener createActionChangeListener(JMenuItem item)
351 return new ActionChangeListener();
355 * Returns true if this popup menu will display its menu item in
356 * a lightweight container and false otherwise.
358 * @return true if this popup menu will display its menu items
359 * in a lightweight container and false otherwise.
361 public boolean isLightWeightPopupEnabled()
363 return lightWeightPopupEnabled;
367 * DOCUMENT ME!
369 * @param enabled DOCUMENT ME!
371 public void setLightWeightPopupEnabled(boolean enabled)
373 lightWeightPopupEnabled = enabled;
377 * Returns label for this popup menu
379 * @return label for this popup menu
381 public String getLabel()
383 return label;
387 * Sets label for this popup menu. This method fires PropertyChangeEvent
388 * when the label property is changed. Please note that most
389 * of the Look & Feel will ignore this property.
391 * @param label label for this popup menu
393 public void setLabel(String label)
395 if (label != this.label)
397 String oldLabel = this.label;
398 this.label = label;
399 firePropertyChange("label", oldLabel, label);
404 * Adds separator to this popup menu
406 public void addSeparator()
408 // insert separator at the end of the list of menu items
409 this.insert(new Separator(), -1);
413 * Adds popupMenuListener to listen for PopupMenuEvents fired
414 * by the JPopupMenu
416 * @param listener PopupMenuListener to add to JPopupMenu
418 public void addPopupMenuListener(PopupMenuListener listener)
420 listenerList.add(PopupMenuListener.class, listener);
424 * Removes PopupMenuListener from JPopupMenu's list of listeners
426 * @param listener PopupMenuListener which needs to be removed
428 public void removePopupMenuListener(PopupMenuListener listener)
430 listenerList.remove(PopupMenuListener.class, listener);
434 * Returns array of PopupMenuListeners that are listening to JPopupMenu
436 * @return Array of PopupMenuListeners that are listening to JPopupMenu
438 public PopupMenuListener[] getPopupMenuListeners()
440 return ((PopupMenuListener[]) listenerList.getListeners(PopupMenuListener.class));
444 * This method calls popupMenuWillBecomeVisible() of popup menu's
445 * PopupMenuListeners. This method is invoked just before popup menu
446 * will appear on the screen.
448 protected void firePopupMenuWillBecomeVisible()
450 EventListener[] ll = listenerList.getListeners(PopupMenuListener.class);
452 for (int i = 0; i < ll.length; i++)
453 ((PopupMenuListener) ll[i]).popupMenuWillBecomeVisible(new PopupMenuEvent(this));
457 * This method calls popupMenuWillBecomeInvisible() of popup
458 * menu's PopupMenuListeners. This method is invoked just before popup
459 * menu will disappear from the screen
461 protected void firePopupMenuWillBecomeInvisible()
463 EventListener[] ll = listenerList.getListeners(PopupMenuListener.class);
465 for (int i = 0; i < ll.length; i++)
466 ((PopupMenuListener) ll[i]).popupMenuWillBecomeInvisible(new PopupMenuEvent(this));
470 * This method calls popupMenuCanceled() of popup menu's PopupMenuListeners.
471 * This method is invoked just before popup menu is cancelled. This happens
472 * when popup menu is closed without selecting any of its menu items. This
473 * usually happens when the top-level window is resized or moved.
475 protected void firePopupMenuCanceled()
477 EventListener[] ll = listenerList.getListeners(PopupMenuListener.class);
479 for (int i = 0; i < ll.length; i++)
480 ((PopupMenuListener) ll[i]).popupMenuCanceled(new PopupMenuEvent(this));
484 * This methods sets popup menu's size to its' preferred size. If the
485 * popup menu's size is previously set it will be ignored.
487 public void pack()
489 // Hook up this call so that it gets executed on the event thread in order
490 // to avoid synchronization problems when calling the layout manager.
491 if (! SwingUtilities.isEventDispatchThread())
493 SwingUtilities.invokeLater(new Runnable()
495 public void run()
497 show();
502 setSize(getPreferredSize());
506 * Return visibility of the popup menu
508 * @return true if popup menu is visible on the screen and false otherwise.
510 public boolean isVisible()
512 return visible;
516 * Sets visibility property of this popup menu. If the property is
517 * set to true then popup menu will be dispayed and popup menu will
518 * hide itself if visible property is set to false.
520 * @param visible true if popup menu will become visible and false otherwise.
522 public void setVisible(final boolean visible)
524 // Hook up this call so that it gets executed on the event thread in order
525 // to avoid synchronization problems when calling the layout manager.
526 if (! SwingUtilities.isEventDispatchThread())
528 SwingUtilities.invokeLater(new Runnable()
530 public void run()
532 setVisible(visible);
537 if (visible == isVisible())
538 return;
540 boolean old = isVisible();
541 this.visible = visible;
542 if (old != isVisible())
544 if (visible)
546 if (invoker != null && !(invoker instanceof JMenu))
548 MenuElement[] menuEls;
549 if (getSubElements().length > 0)
551 menuEls = new MenuElement[2];
552 menuEls[0] = this;
553 menuEls[1] = getSubElements()[0];
555 else
557 menuEls = new MenuElement[1];
558 menuEls[0] = this;
560 MenuSelectionManager.defaultManager().setSelectedPath(menuEls);
562 firePopupMenuWillBecomeVisible();
563 PopupFactory pf = PopupFactory.getSharedInstance();
564 pack();
565 popup = pf.getPopup(invoker, this, popupLocationX, popupLocationY);
566 popup.show();
568 else
570 getSelectionModel().clearSelection();
571 firePopupMenuWillBecomeInvisible();
572 popup.hide();
574 firePropertyChange("visible", old, isVisible());
579 * Sets location of the popup menu.
581 * @param x X coordinate of the popup menu's location
582 * @param y Y coordinate of the popup menu's location
584 public void setLocation(int x, int y)
586 popupLocationX = x;
587 popupLocationY = y;
588 // Handle the case when the popup is already showing. In this case we need
589 // to fetch a new popup from PopupFactory and use this. See the general
590 // contract of the PopupFactory.
594 * Returns popup menu's invoker.
596 * @return popup menu's invoker
598 public Component getInvoker()
600 return invoker;
604 * Sets popup menu's invoker.
606 * @param component The new invoker of this popup menu
608 public void setInvoker(Component component)
610 invoker = component;
614 * This method displays JPopupMenu on the screen at the specified
615 * location. Note that x and y coordinates given to this method
616 * should be expressed in terms of the popup menus' invoker.
618 * @param component Invoker for this popup menu
619 * @param x x-coordinate of the popup menu relative to the specified invoker
620 * @param y y-coordiate of the popup menu relative to the specified invoker
622 public void show(Component component, int x, int y)
624 if (component.isShowing())
626 setInvoker(component);
627 Point p = new Point(x, y);
628 SwingUtilities.convertPointToScreen(p, component);
629 setLocation(p.x, p.y);
630 setVisible(true);
635 * Returns component located at the specified index in the popup menu
637 * @param index index of the component to return
639 * @return component located at the specified index in the popup menu
641 * @deprecated Replaced by getComponent(int)
643 public Component getComponentAtIndex(int index)
645 return getComponent(index);
649 * Returns index of the specified component in the popup menu
651 * @param component Component to look for
653 * @return index of the specified component in the popup menu
655 public int getComponentIndex(Component component)
657 Component[] items = getComponents();
659 for (int i = 0; i < items.length; i++)
661 if (items[i].equals(component))
662 return i;
665 return -1;
669 * Sets size of the popup
671 * @param size Dimensions representing new size of the popup menu
673 public void setPopupSize(Dimension size)
675 super.setSize(size);
679 * Sets size of the popup menu
681 * @param width width for the new size
682 * @param height height for the new size
684 public void setPopupSize(int width, int height)
686 super.setSize(width, height);
690 * Selects specified component in this popup menu.
692 * @param selected component to select
694 public void setSelected(Component selected)
696 int index = getComponentIndex(selected);
697 selectionModel.setSelectedIndex(index);
701 * Checks if this popup menu paints its border.
703 * @return true if this popup menu paints its border and false otherwise.
705 public boolean isBorderPainted()
707 return borderPainted;
711 * Sets if the border of the popup menu should be
712 * painter or not.
714 * @param painted true if the border should be painted and false otherwise
716 public void setBorderPainted(boolean painted)
718 borderPainted = painted;
722 * Returns margin for this popup menu.
724 * @return margin for this popup menu.
726 public Insets getMargin()
728 return margin;
732 * A string that describes this JPopupMenu. Normally only used
733 * for debugging.
735 * @return A string describing this JMenuItem
737 protected String paramString()
739 StringBuffer sb = new StringBuffer();
740 sb.append(super.paramString());
741 sb.append(",label=");
742 if (getLabel() != null)
743 sb.append(getLabel());
744 sb.append(",lightWeightPopupEnabled=").append(isLightWeightPopupEnabled());
745 sb.append(",margin=");
746 if (getMargin() != null)
747 sb.append(margin);
748 sb.append(",paintBorder=").append(isBorderPainted());
749 return sb.toString();
753 * Process mouse events forwarded from MenuSelectionManager. This method
754 * doesn't do anything. It is here to conform to the MenuElement interface.
756 * @param event event forwarded from MenuSelectionManager
757 * @param path path to the menu element from which event was generated
758 * @param manager MenuSelectionManager for the current menu hierarchy
760 public void processMouseEvent(MouseEvent event, MenuElement[] path,
761 MenuSelectionManager manager)
763 // Empty Implementation. This method is needed for the implementation
764 // of MenuElement interface
768 * Process key events forwarded from MenuSelectionManager. This method
769 * doesn't do anything. It is here to conform to the MenuElement interface.
771 * @param event event forwarded from MenuSelectionManager
772 * @param path path to the menu element from which event was generated
773 * @param manager MenuSelectionManager for the current menu hierarchy
776 public void processKeyEvent(KeyEvent event, MenuElement[] path,
777 MenuSelectionManager manager)
779 // Empty Implementation. This method is needed for the implementation
780 // of MenuElement interface
784 * Method of MenuElement Interface. It is invoked when
785 * popupMenu's selection has changed
787 * @param changed true if this popupMenu is part of current menu
788 * hierarchy and false otherwise.
790 public void menuSelectionChanged(boolean changed)
792 if (! changed)
793 setVisible(false);
797 * Return subcomonents of this popup menu. This method returns only
798 * components that implement the <code>MenuElement</code> interface.
800 * @return array of menu items belonging to this popup menu
802 public MenuElement[] getSubElements()
804 Component[] items = getComponents();
805 ArrayList subElements = new ArrayList();
807 for (int i = 0; i < items.length; i++)
808 if (items[i] instanceof MenuElement)
809 subElements.add(items[i]);
811 return (MenuElement[])
812 subElements.toArray(new MenuElement[subElements.size()]);
816 * Method of the MenuElement interface. Returns reference to itself.
818 * @return Returns reference to itself
820 public Component getComponent()
822 return this;
826 * Checks if observing mouse event should trigger popup
827 * menu to show on the screen.
829 * @param event MouseEvent to check
831 * @return true if the observing mouse event is popup trigger and false otherwise
833 public boolean isPopupTrigger(MouseEvent event)
835 return ((PopupMenuUI) getUI()).isPopupTrigger(event);
839 * DOCUMENT ME!
841 * @return DOCUMENT ME!
843 public AccessibleContext getAccessibleContext()
845 if (accessibleContext == null)
846 accessibleContext = new AccessibleJPopupMenu();
848 return accessibleContext;
852 * This is the separator that can be used in popup menu.
854 public static class Separator extends JSeparator
856 public Separator()
858 super();
861 public String getUIClassID()
863 return "PopupMenuSeparatorUI";
867 protected class AccessibleJPopupMenu extends AccessibleJComponent
869 private static final long serialVersionUID = 7423261328879849768L;
871 protected AccessibleJPopupMenu()
873 // Nothing to do here.
876 public AccessibleRole getAccessibleRole()
878 return AccessibleRole.POPUP_MENU;
882 /* This class resizes popup menu and repaints popup menu appropriately if one
883 of item's action has changed */
884 private class ActionChangeListener implements PropertyChangeListener
886 public void propertyChange(PropertyChangeEvent evt)
888 // We used to have a revalidate() and repaint() call here. However I think
889 // this is not needed. Instead, a new Popup has to be fetched from the
890 // PopupFactory and used here.