Creating a HUD style comob box

March 8, 2009

hud_combo_box1

Creating a custom combo box is by far the most complicated of the custom components we’ve discussed thus far. BasicComboBoxUI encapsulates a large amount of functionality, including building and showing a popup, which it delegates to a ComboPopup.

The ComboPopup is responsible for figuring out where to place the popup on the screen and then showing it. BasicComboPopup is used by BasicComboBoxUI, and puts the popup directly below the comb box. We want the popup to show over the popup such that the selected item lines up with the combo box.

One other important note about ComboPopup is that it wants the items in the popup to be contained in a JList. This is not good if we’re on Mac OS X and want the blue gradient menu selection, as JList, by default, has a flat blue selection color. This is another reason we’ll need to create a custom implementation of ComboPopup, namely so we can fill it with JMenuItems instead of a JList.

Listed first below is an extension of BasicComboBoxUI, which takes responsibility for drawing the combo box itself. It does this by creating a simple HUD style button (see this post for the HudButtonUI code), with extra margin space on the right. Up/down arrows are then painted in the extra space on the right.

The second listing is a custom implementation of ComboPopup. This implementation uses JMenuItems instead of a JList. It also figures out where to place the popup on the screen. Note that the given implementation won’t handle cases where the popup is to large to fit on the screen.

HudComboBoxUI:

public class HudComboBoxUI extends BasicComboBoxUI {

    /* Font constants. */
    public static final float FONT_SIZE = 11.0f;
    public static final Color FONT_COLOR = Color.WHITE;

    private HudButtonUI fArrowButtonUI;

    private static final int LEFT_MARGIN = 7;
    private static final int RIGHT_MARGIN = 19;
    private static final int DEFAULT_WIDTH = 100;

    /**
     * Creates a HUD style {@link javax.swing.plaf.ComboBoxUI}.
     */
    public HudComboBoxUI() {
        fArrowButtonUI = new HudButtonUI(Roundedness.COMBO_BUTTON);
    }

    @Override
    protected void installDefaults() {
        super.installDefaults();

        comboBox.setFont(getHudFont());
        comboBox.setForeground(FONT_COLOR);
        comboBox.setOpaque(false);
        comboBox.addActionListener(createComboBoxListener());
    }

    @Override
    protected void uninstallDefaults() {
        super.uninstallDefaults();
        // TODO implement this.
    }

    @Override
    protected void installComponents() {
        super.installComponents();
        updateDisplayedItem();
    }

    /**
     * Updates the value displayed to match that of 
     * {@link javax.swing.JComboBox#getSelectedItem()}.
     */
    private void updateDisplayedItem() {
        // TODO make the calculation of the display string more robust
        // TODO (i.e. use TextProvider interface).
        String displayValue = comboBox.getSelectedItem() == null
                ? "" : comboBox.getSelectedItem().toString();
        arrowButton.setText(displayValue);
    }

    /**
     * Creates a {@link EPComboPopup.ComboBoxVerticalCenterProvider} 
     * that returns a vertical center value that takes HudComboBoxUI's drop 
     * shadow. The visual center is calculated as if the drop shadow did not exist.
     */
    private EPComboPopup.ComboBoxVerticalCenterProvider createComboBoxVerticalCenterProvider() {
        return new EPComboPopup.ComboBoxVerticalCenterProvider() {
            public int provideCenter(JComboBox comboBox) {
                return calculateArrowButtonVisualVerticalCenter();
            }
        };
    }

    /**
     * Creates an {@link java.awt.event.ActionListener} that updates 
     * the displayed item when the {@link JComboBox}'s currently selected 
     * item changes.
     */
    private ActionListener createComboBoxListener() {
        return new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                updateDisplayedItem();
            }
        };
    }

    @Override
    protected JButton createArrowButton() {
        JButton arrowButton = new JButton("");
        arrowButton.setUI(fArrowButtonUI);
        Insets currentInsets = arrowButton.getInsets();
        arrowButton.setBorder(BorderFactory.createEmptyBorder(
                currentInsets.top, LEFT_MARGIN, currentInsets.bottom, RIGHT_MARGIN));
        arrowButton.setHorizontalAlignment(SwingConstants.LEFT);

        return arrowButton;
    }

    @Override
    protected ListCellRenderer createRenderer() {
        return new JComboBox().getRenderer();
    }

    @Override
    protected ComboPopup createPopup() {
        EPComboPopup popup = new EPComboPopup(comboBox);
        popup.setFont(getHudFont().deriveFont(Font.PLAIN));
        // install a custom ComboBoxVerticalCenterProvider that takes into 
        // account the size of the drop shadow.
        popup.setVerticalComponentCenterProvider(createComboBoxVerticalCenterProvider());
        return popup;
    }

    @Override
    public Dimension getMinimumSize(JComponent c) {
        int width = getDisplaySize().width;
        int height = arrowButton.getPreferredSize().height;
        return new Dimension(width, height);
    }

    @Override
    protected Dimension getDefaultSize() {
        JButton button = new JButton("Button");
        button.setUI(new HudButtonUI());
        return new Dimension(DEFAULT_WIDTH, button.getPreferredSize().height);
    }

    @Override
    public void paint(Graphics g, JComponent c) {
        super.paint(g, c);

        Graphics2D graphics = (Graphics2D) g.create();
        paintUpDownArrowsIcon(graphics);
        graphics.dispose();
    }

    @Override
    public void paintCurrentValue(Graphics g, Rectangle bounds, boolean hasFocus) {
        // no painting necessary - the arrowButton handles painting of the currently selected value.
    }

    @Override
    protected Dimension getDisplaySize() {
        int maxWidth;
        if (comboBox.getPrototypeDisplayValue() != null) {
            maxWidth = getDisplayWidth(comboBox.getPrototypeDisplayValue());
        } else if (comboBox.getItemCount() > 0) {
            maxWidth = getMaxComboBoxModelDisplayWidth();
        } else {
            maxWidth = getDefaultSize().width;
        }

        Insets arrowButtonInsets = arrowButton.getInsets();
        maxWidth += arrowButtonInsets.left + arrowButtonInsets.right;

        return new Dimension(maxWidth, arrowButton.getPreferredSize().height);
    }

    /**
     * Gets the max display width in pixels of all entries in the {@link JComboBox}'s
     * {@link javax.swing.ComboBoxModel}.
     */
    private int getMaxComboBoxModelDisplayWidth() {
        int maxWidth = 0;
        for (int i = 0; i < comboBox.getModel().getSize(); i++) {
            int itemWidth = getDisplayWidth(comboBox.getModel().getElementAt(i));
            maxWidth = Math.max(maxWidth, itemWidth);
        }
        return maxWidth;
    }

    /**
     * Calculates the display width in pixels of the given object.
     */
    private int getDisplayWidth(Object object) {
        assert object != null : "The given object cannot be null";
        // TODO refactor this logic into utility class that looks for TextProvider.
        FontMetrics fontMetrics = comboBox.getFontMetrics(comboBox.getFont());
        return fontMetrics.stringWidth(object.toString());
    }

    @Override
    protected LayoutManager createLayoutManager() {
        return new LayoutManager() {
            public void addLayoutComponent(String name, Component comp) {
                throw new UnsupportedOperationException("This operation is not supported.");
            }

            public void removeLayoutComponent(Component comp) {
                throw new UnsupportedOperationException("This operation is not supported.");
            }

            public Dimension preferredLayoutSize(Container parent) {
                // the combo box's preferred size is the preferred width of the parent and the
                // preferred height of the arrowButton.
                return new Dimension(parent.getPreferredSize().width,
                        arrowButton.getPreferredSize().height);
            }

            public Dimension minimumLayoutSize(Container parent) {
                return parent.getMinimumSize();
            }

            public void layoutContainer(Container parent) {
                // make the arrowButton fill the width, and center itself in the available height.
                int buttonHeight = arrowButton.getPreferredSize().height;
                int y = parent.getHeight() / 2 - buttonHeight / 2;
                arrowButton.setBounds(0, y, parent.getWidth(), buttonHeight);
            }
        };
    }

    /**
     * Calculates the visual vertical center of this component. The visual center is what the user
     * would interpret as the center, thus we adjust the actual center to take into account the size
     * of the drop shadow.
     */
    private int calculateArrowButtonVisualVerticalCenter() {
        int arrowButtonShadowHeight = getHudControlShadowSize();
        return (arrowButton.getHeight() - arrowButtonShadowHeight) / 2;
    }

    /**
     * Paints the up and down arrows on the right side of the combo box.
     */
    private void paintUpDownArrowsIcon(Graphics2D graphics) {
        Insets arrowButtonInsets = arrowButton.getInsets();
        int arrowButtonHeight = arrowButton.getHeight();

        // calculate the exact center of where both arrows will be drawn relative to.
        int centerX = arrowButton.getWidth() - arrowButtonInsets.right / 2;
        int centerY = calculateArrowButtonVisualVerticalCenter();

        // calculate how many pixels there should be between the arrows as well as how long each
        // side of the arrow should be.
        int verticalDistanceBetweenArrows = (int) (arrowButtonHeight * 0.125);
        int arrowSideLength = verticalDistanceBetweenArrows * 2;

        // calculate the upper left position of the up arrow.
        int upArrowX = centerX - arrowSideLength / 2;
        int upArrowY = centerY - verticalDistanceBetweenArrows / 2;

        graphics.setColor(FONT_COLOR);
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // translate the graphics to the upper left of each arrow and draw that arrow. each arrow
        // assumes that it is being drawn at 0,0.
        graphics.translate(upArrowX, upArrowY);
        graphics.fill(createUpArrow(arrowSideLength));
        graphics.translate(0, verticalDistanceBetweenArrows);
        graphics.fill(createDownArrow(arrowSideLength));
    }

    /**
     * Creates a path representing an up arrow, based at 0,0.
     */
    private static GeneralPath createUpArrow(int arrowSideLength) {
        GeneralPath path = new GeneralPath();
        path.moveTo(0, 0);
        path.lineTo(arrowSideLength, 0);
        path.lineTo(arrowSideLength / 2, -arrowSideLength);
        path.closePath();

        return path;
    }

    /**
     * Creates a path representing a down arrow, based at 0,0.
     */
    private static GeneralPath createDownArrow(int arrowSideLength) {
        GeneralPath path = new GeneralPath();
        path.moveTo(0, 0);
        path.lineTo(arrowSideLength, 0);
        path.lineTo(arrowSideLength / 2, arrowSideLength);
        path.closePath();

        return path;
    }

    /**
     * Gets the number of pixels that a HUD style widget's shadow takes up. HUD
     * button's have a shadow directly below them, that is, there is no top, left
     * or right component to the shadow.
     * @return the number of pixels that a HUD style widget's shadow takes up.
     */
    private static int getHudControlShadowSize() {
        // this is hardcoded at two pixels for now, but ideally it would be
        // calculated.
        return 2;
    }

    /**
     * Gets the font used by HUD style widgets.
     * @return the font used by HUD style widgets.
     */
    private static Font getHudFont() {
        return UIManager.getFont("Button.font").deriveFont(Font.BOLD, FONT_SIZE);
    }

    /**
     * An enumeration representing the roundness styles of HUD buttons. Using this
     * enumeration will make it easier to transition this code to support more
     * HUD controls, like check boxes and combo buttons.
     */
    public enum Roundedness {
        /**
         * A roundedness of 95%, equates to almost a half-circle as the button
         * edge shape.
         */
        ROUNDED_BUTTON(.95),
        /**
         * A roundedness of 95%, equates to almost a half-circle as the button
         * edge shape.
         */
        COMBO_BUTTON(.45);

        private final double fRoundedPercentage;

        private Roundedness(double roundedPercentage) {
            fRoundedPercentage = roundedPercentage;
        }

        public int getRoundedDiameter(int controlHeight) {
            int roundedDiameter = (int) (controlHeight * fRoundedPercentage);
            // force the rounded diameter value to be even - odd values look lumpy.
            int makeItEven = roundedDiameter % 2;
            return roundedDiameter - makeItEven;
        }
    }
}

EPComboPopup:

public class EPComboPopup implements ComboPopup {

    private final JComboBox fComboBox;
    private JPopupMenu fPopupMenu = new JPopupMenu();
    private Font fFont;
    private ComboBoxVerticalCenterProvider fComboBoxVerticalCenterProvider =
            new DefaultVerticalCenterProvider();

    private static final int LEFT_SHIFT = 5;

    public EPComboPopup(JComboBox comboBox) {
        fComboBox = comboBox;
        fFont = comboBox.getFont();
    }

    public void setFont(Font font) {
        fFont = font;
    }

    public void setVerticalComponentCenterProvider(
            ComboBoxVerticalCenterProvider comboBoxVerticalCenterProvider) {
        if (comboBoxVerticalCenterProvider == null) {
            throw new IllegalArgumentException(
                    "The given CompnonentCenterProvider cannot be null.");
        }
        fComboBoxVerticalCenterProvider = comboBoxVerticalCenterProvider;
    }

    private void togglePopup() {
        if (isVisible()) {
            hide();
        } else {
            show();
        }
    }

    private void clearAndFillMenu() {
        fPopupMenu.removeAll();

        ButtonGroup buttonGroup = new ButtonGroup();

        // add the given items to the popup menu.
        for (int i = 0; i < fComboBox.getModel().getSize(); i++) {
            Object item = fComboBox.getModel().getElementAt(i);
            JMenuItem menuItem = new JCheckBoxMenuItem(item.toString());
            menuItem.setFont(fFont);
            menuItem.addActionListener(createMenuItemListener(item));
            buttonGroup.add(menuItem);
            fPopupMenu.add(menuItem);

            // if the current item is selected, make the menu item reflect that.
            if (item.equals(fComboBox.getModel().getSelectedItem())) {
                menuItem.setSelected(true);
                fPopupMenu.setSelected(menuItem);
            }
        }

        fPopupMenu.pack();
        int popupWidth = fComboBox.getWidth() + 5;
        int popupHeight = fPopupMenu.getPreferredSize().height;
        fPopupMenu.setPreferredSize(new Dimension(popupWidth, popupHeight));
    }

    private ActionListener createMenuItemListener(final Object comboBoxItem) {
        return new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                fComboBox.setSelectedItem(comboBoxItem);
            }
        };
    }

    private void forceCorrectPopupSelection() {
        assert fPopupMenu.isShowing() : 
                "The popup must be showing for this method to work properly.";

        // force the correct item to be shown as selected. this is a
        // work around for Java bug 4740942, which has been fixed by
        // Sun, but not by Apple.
        int index = fPopupMenu.getSelectionModel().getSelectedIndex();
        MenuElement[] menuPath = new MenuElement[2];
        menuPath[0] = fPopupMenu;
        menuPath[1] = fPopupMenu.getSubElements()[index];
        MenuSelectionManager.defaultManager().setSelectedPath(menuPath);
    }

    // ComboPopup implementation. ///////////////////////////////////////////

    public void show() {
        clearAndFillMenu();
        Rectangle popupBounds = calculateInitialPopupBounds();

        fPopupMenu.show(fComboBox, popupBounds.x, popupBounds.y);
        forceCorrectPopupSelection();
    }

    public void hide() {
        fPopupMenu.setVisible(false);
    }

    public boolean isVisible() {
        return fPopupMenu.isVisible();
    }

    /**
     * This method is not implemented and would throw an 
     * {@link UnsupportedOperationException} if 
     * {@link javax.swing.plaf.basic.BasicComboBoxUI} didn't call it. Thus, 
     * this method should not be used, as it always returns null.
     *
     * @return null.
     */
    public JList getList() {
        return null;
    }

    public MouseListener getMouseListener() {
        return new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                // TODO add more detailed logic.
                togglePopup();
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                MenuSelectionManager.defaultManager().processMouseEvent(e);
            }
        };
    }

    public MouseMotionListener getMouseMotionListener() {
        return new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                MenuSelectionManager.defaultManager().processMouseEvent(e);
            }
        };
    }

    public KeyListener getKeyListener() {
        return null;
    }

    public void uninstallingUI() {
        // TODO implement, if necessary.
    }

    /**
     * An interface to allow a third-party to provide the center of a given 
     * compoennt.
     */
    public interface ComboBoxVerticalCenterProvider {
        int provideCenter(JComboBox comboBox);
    }

    // A default implementation of ComboBoxVerticalCenterProvider. ///////////

    private static class DefaultVerticalCenterProvider 
            implements ComboBoxVerticalCenterProvider {
        public int provideCenter(JComboBox comboBox) {
            return comboBox.getHeight() / 2;
        }
    }

    // Utility methods. //////////////////////////////////////////////////////

    private Rectangle calculateInitialPopupBounds() {
        // grab the right most location of the button.
        int comboBoxRightEdge = fComboBox.getWidth();

        // figure out how the height of a menu item.
        Insets insets = fPopupMenu.getInsets();

        // calculate the x and y value at which to place the popup menu. by 
        // default, this will place the selected menu item in the popup item 
        // directly over the button.
        int x = comboBoxRightEdge - fPopupMenu.getPreferredSize().width - LEFT_SHIFT;
        int selectedItemIndex = 
                fPopupMenu.getSelectionModel().getSelectedIndex();
        int componentCenter = 
                fComboBoxVerticalCenterProvider.provideCenter(fComboBox);
        int menuItemHeight = 
                fPopupMenu.getComponent(selectedItemIndex).getPreferredSize().height;
        int menuItemCenter = 
                insets.top + (selectedItemIndex * menuItemHeight) + menuItemHeight / 2;
        int y = componentCenter - menuItemCenter;

        // TODO this method doesn't robustly handle multiple monitors.

        return new Rectangle(new Point(x,y), fPopupMenu.getPreferredSize());
    }
}
Advertisements

13 Responses to “Creating a HUD style comob box”


  1. […] Coming into my feed reader after posting this blog, I thought I’d quickly add that Ken Orr has a blog post about creating a custom HUD-style combo box. […]

  2. zammbi Says:

    Just tested out the comboBox, why is the popup not themed? Just looks terrible. Btw you spelled the title of this news post wrong :)

    • Ken Says:

      The popup on the HUD combo box in Apple apps isn’t themed, thus mine is not themed.

      • zammbi Says:

        Oh ok. Just the ocean theme does not look good with the HUD controls. So much that I can’t use it in my app.
        I guess it looks fine with the mac look and feel? but I need this app looking good for windows too.

      • Ken Says:

        The HUD controls should only be used on a HUD window, which looks the same across platforms.

      • zammbi Says:

        Can’t seem to reply to your comment. So I’ll rely here.
        I am placing the control in the HUD Window. The control itself looks fine, its just the popup menu doesn’t.

  3. Brandon Says:

    Why does it render improperly when I make a selection. When I click it, the whole box turns grey.

    • Ken Says:

      Make sure you haven’t made the button opaque, and make sure the container that the button is in is marked as non-opaque: setOpaque(false).

  4. Mario Says:

    What’s the use agreement with this code? Do you have a license or are you releasing this into the wild?

    btw, I do like it…good job and thanks.

    • Mario Says:

      nevermind…saw your “about” page comment where you reference the LGPL license and having thank you credit to you. Thanks.

      • Ken Says:

        Hi Mario,

        I’m pretty flexible. If you need it released under a license other than LGPL, I can do that.

  5. Mario Says:

    Ken,

    I actually don’t know what license I’d need, to be honest. But I’ll probably let you know either way. I’m using it in a code at NASA – Johnson Space Center for a 2D map projection selection menu and it fits nearly perfectly with what I needed. I had to do some tweaks like change the JCheckBoxMenuItem to JRadioButtonMenuItem but that’s about it. Thanks a lot for releasing code and again, I’ll let you know as soon as I’m told if LGPL will be fine or not.

    Mario.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: