001 /*
002 * Copyright 2002-2004 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
005 * use this file except in compliance with the License. You may obtain a copy of
006 * the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
012 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
013 * License for the specific language governing permissions and limitations under
014 * the License.
015 */
016 package org.springframework.richclient.util;
017
018 import java.awt.Dimension;
019
020 import javax.swing.AbstractButton;
021 import javax.swing.JMenuItem;
022 import javax.swing.JPopupMenu;
023 import javax.swing.MenuElement;
024
025 import org.springframework.richclient.image.EmptyIcon;
026
027 public class MenuElementUtils {
028 private MenuElementUtils() {
029 }
030
031 /**
032 * Return whether there are any icons at the moment.
033 *
034 * @return whether there are any icons at the moment
035 */
036 private static boolean hasIcons(MenuElement menuElement) {
037 MenuElement[] elements = menuElement.getSubElements();
038 for (int i = 0; i < elements.length; i++) {
039 MenuElement element = elements[i];
040 if (element instanceof JMenuItem && (((JMenuItem)element).getIcon() != null)) {
041 return true;
042 }
043 if (element instanceof JPopupMenu) {
044 return hasIcons(element);
045 }
046 }
047 return false;
048 }
049
050 /**
051 * Fill in icons (if there is no icon, put in an empty icon).
052 */
053 private static void fillInIcons(MenuElement menuElement) {
054 MenuElement[] elements = menuElement.getSubElements();
055 for (int i = 0; i < elements.length; i++) {
056 MenuElement element = elements[i];
057 if (element instanceof JMenuItem) {
058 JMenuItem menu = (JMenuItem)element;
059 if (menu.getIcon() == null) {
060 menu.setIcon(EmptyIcon.SMALL);
061 }
062 }
063 if (element instanceof JPopupMenu) {
064 fillInIcons(element);
065 }
066 }
067 }
068
069 /**
070 * Align the icons.
071 */
072 public static void alignIcons(MenuElement menuElement) {
073 // We fill in a blank icon to align the menu items
074 if (hasIcons(menuElement)) {
075 fillInIcons(menuElement);
076 }
077 }
078
079 public static void showButtonPopupMenu(AbstractButton button, JPopupMenu popup) {
080 if (!popup.isVisible()) {
081 Dimension size = button.getSize();
082 popup.show(button, 0, size.height);
083 }
084 }
085
086 }