Someone recently requested I add a HUD style slider to the widget set, which I quickly added and is now available in the latest Mac Widgets for Java developer build. Creating a custom SliderUI delegate is pretty easy, as BasicSliderUI has all the right hooks. You can specify the thumb size, tick size, track bounds, thumb location and much more by overriding corresponding methods. This is a refreshing change from the complicated process of creating a custom scroll bar UI delegate (which I talked about in detail in part 1, part 2, and part 3 of the “Skinning a scroll bar” series).

As I’ve noted in previous HUD style component posts (here and here), you may notice a bit of redundant code between the posts. I’ve done this to keep the blog entries independent, but the actual Mac Widgets for Java code uses a utility class to do most of the HUD painting.

Finally, for this widget to look “correct”, it must be added to a HUD style window, which I talked about here.

public class HudSliderUI extends BasicSliderUI {

    private static final int SLIDER_KNOB_WIDTH = 11;
    private static final int SLIDER_KNOB_HEIGHT_NO_TICKS = 11;
    private static final int SLIDER_KNOB_HEIGHT_WITH_TICKS = 13;
    private static final int TRACK_HEIGHT = 4;

    private static final Color TRACK_BACKGROUND_COLOR = new Color(143, 147, 144, 100);
    private static final Color TRACK_BORDER_COLOR = new Color(255, 255, 255, 200);

    private static final Color TOP_SLIDER_KNOB_COLOR = new Color(0x555555);
    private static final Color BOTTOM_SLIDER_KNOB_COLOR = new Color(0x393939);
    private static final Color TOP_SLIDER_KNOB_PRESSED_COLOR = new Color(0xb0b2b6);
    private static final Color BOTTOM_SLIDER_KNOB_PRESSED_COLOR = new Color(0x86888b);

    public static final Color BORDER_COLOR = new Color(0xc5c8cf);

    private static final Color LIGHT_SHADOW_COLOR = new Color(0, 0, 0, 145);
    private static final Color DARK_SHADOW_COLOR = new Color(0, 0, 0, 50);

    private static final ShapeProvider NO_TICKS_SHAPE_PROVIDER =

    private static final ShapeProvider TICKS_SHAPE_PROVIDER =

    public HudSliderUI(JSlider b) {

    protected void installDefaults(JSlider slider) {

    protected Dimension getThumbSize() {
        int sliderKnobHeight = slider.getPaintTicks()
        return new Dimension(SLIDER_KNOB_WIDTH, sliderKnobHeight);

    public void paintThumb(Graphics graphics) {
        Paint paint = createSliderKnobButtonPaint(isDragging(), thumbRect.height);
        ShapeProvider shapeProvider = slider.getPaintTicks()
        paintHudControlBackground((Graphics2D) graphics, thumbRect, shapeProvider,

    public void paintTrack(Graphics graphics) {
        Graphics2D graphics2d = (Graphics2D) graphics;
                RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        double trackY = slider.getHeight()/2.0 - TRACK_HEIGHT/2.0;
        RoundRectangle2D track = new RoundRectangle2D.Double(
                0, trackY, slider.getWidth()-1, TRACK_HEIGHT - 1, 4, 2);


    protected int getTickLength() {
        return 5;

    protected void calculateThumbLocation() {

        // if this is a horizontal style slider and we're drawing a pointy style thumb
        // then shift the thumb down three pixels.
        if ( slider.getOrientation() == JSlider.HORIZONTAL
                && slider.getPaintTicks()) {
            thumbRect.y += 3;
        } else  {
            // TODO handle vertical slider.

    protected void calculateTickRect() {

        // if this is a horizontal style slider, shift the ticks down one pixel so that
        // they aren't right up against the track.
        if ( slider.getOrientation() == JSlider.HORIZONTAL ) {
            tickRect.y += 1;
        } else  {
            // TODO handle vertical slider.

    protected void paintMajorTickForHorizSlider(Graphics g, Rectangle tickBounds, int x) {
        super.paintMajorTickForHorizSlider(g, tickBounds, x);

    public void setThumbLocation(int x, int y) {
        super.setThumbLocation(x, y);
        // repaint the whole slider -- it's easier than trying to figure out
        // whats dirty, especially since the thumb will be drawn outside of the
        // thumbRect (the shadow part).

    public void paintFocus(Graphics g) {
        // don't paint focus.

    private static Paint createSliderKnobButtonPaint(boolean isPressed, int height) {
        // grab the top and bottom gradient colors based on the pressed state.
        Color topColor = isPressed
        Color bottomColor = isPressed
        // compenstate for the two pixel shadow drawn below the slider thumb.
        int bottomY = height - 2;
        return new GradientPaint(0, 0, topColor, 0, bottomY, bottomColor);

     * Creates a simple circle.
    private static ShapeProvider createCircularSliderKnobShapeProvider() {
        return new ShapeProvider() {
            public Shape createShape(double x, double y, double width, double height) {
                return new Ellipse2D.Double(x, y, width, height);

     * Cerates a pointy slider thumb shape that looks roughly like this:
     *     +----+
     *    /      \
     *    +      +
     *    |      |
     *    +      +
     *      \  /
     *       \/
    private static ShapeProvider createPointedSliderKnobShapeProvider() {
        return new ShapeProvider() {
            public Shape createShape(double x, double y, double width, double height) {
                float xFloat = (float) x;
                float yFloat = (float) y;
                float widthFloat = (float) width;
                float heightFloat = (float) height;

                // draw the thumb shape based on the given height and width.
                GeneralPath path = new GeneralPath();
                // move in two pixels so that we can curve down to the next point.
                path.moveTo(xFloat + 2.0f, yFloat);
                // curve down to the second point.
                path.curveTo(xFloat + 0.25f, yFloat + 0.25f, xFloat - 0.25f,
                        yFloat + 2.0f, xFloat, yFloat + 2.0f);
                // move straight down to the next point.
                path.lineTo(xFloat, yFloat + heightFloat/1.60f);
                // move down and right to form the left half of the pointy section.
                path.lineTo(xFloat + widthFloat/2, yFloat + heightFloat);
                // move up and right to form the right half of the pointy section.
                path.lineTo(xFloat + widthFloat, yFloat + heightFloat/1.60f);
                // move straight up to the point to curve from.
                path.lineTo(xFloat + widthFloat, yFloat + 2.0f);
                // curve up and right to the top of the thumb.
                path.curveTo(xFloat + widthFloat - 0.25f, yFloat + 2.0f,
                        xFloat + widthFloat - 0.25f, yFloat + 0.25f,
                        xFloat + widthFloat - 2.0f, yFloat);

                return path;

     * Paints a HUD style background in the given shape. This includes a drop shadow
     * which will be drawn under the shape to be painted. The shadow will be draw
     * outside the given bounds.
     * @param graphics the {@code Graphics2D} context to draw in.
     * @param bounds the bounds to paint in.
     * @param shapeProvider the delegate to request the {@link Shape} from.
     * @param paint the {@link Paint} to use to fill the {@code Shape}.
    public static void paintHudControlBackground(
            Graphics2D graphics, Rectangle bounds, ShapeProvider shapeProvider,
            Paint paint) {


        int x = bounds.x;
        int y = bounds.y;
        int width = bounds.width;
        int height = bounds.height;

        // paint the first (further away) part of the drop shadow.
        graphics.draw(shapeProvider.createShape(x, y, width - 1, height));
        // paint the second (closer) part of the drop shadow.
        graphics.draw(shapeProvider.createShape(x, y, width - 1, height + 1));

        // fill the HUD shape.
        graphics.fill(shapeProvider.createShape(x, y + 1, width, height - 1));
        // stroke the HUD shape.
        graphics.draw(shapeProvider.createShape(x, y, width - 1, height - 1));

     * An interface for specifying a shape to paint and draw a drop shadown under.
    public interface ShapeProvider {
        Shape createShape(double x, double y, double width, double height);

There are a few new client properties on the Mac, that haven’t yet been documented (though I’ve been assured that they’re safe to use). The great thing about the way Apple has been using client properties on the Mac, is that they make it easy for you to get closer to being a great Mac app, while not breaking your fidelity on other platforms. They’re really great if you want to fit in on your target platform, whereas in Mac Widgets for Java, I’m aiming for always looking like a Mac app.

The screenshots above show the new client properties that give you access to SourceList style selection painters (demo’d in the source code below). Note that these painters accurately pick up whether the user is using Aqua or Graphite — that’s a big bonus.

Here’s a listing of the new client properties:


Here’s a little bit of code that puts a few of the new SourceList client properties to work (seen above):

public class NewClientProperties {

     * Create a SourceList style JList.
    private static JList createMacSourceList() {
        JList list = new SourceList();
        // install a custom renderer that wraps the already installed renderer.
        list.setCellRenderer(new CustomListCellRenderer(list.getCellRenderer()));
        return list;

     * A custom JList that renders like a Mac SourceList.
    public static class SourceList extends JList {

        public SourceList() {
            // make the component non-opaque so that we can paint the background in
            // paintComponent.

        protected void paintComponent(Graphics g) {
            // paint the background of the component using the special Mac border
            // painter.
            Border backgroundPainter =
            backgroundPainter.paintBorder(this, g, 0, 0, getWidth(), getHeight());

     * A custom ListCellRenderrer that wraps a delegate renderer.
    public static class CustomListCellRenderer extends JPanel
            implements ListCellRenderer {

        private ListCellRenderer fDelegate;
        private boolean fIsSelected;
        private boolean fIsFocused;

        public CustomListCellRenderer(ListCellRenderer delegate) {
            this.setLayout(new BorderLayout());
            fDelegate = delegate;

        public Component getListCellRendererComponent(
                JList list, Object value, int index,boolean isSelected,
                boolean cellHasFocus) {

            // remember the isSelected and cellHasFocus state so that we can use those
            // values in the paintComponent method.
            fIsSelected = isSelected;
            fIsFocused = cellHasFocus;
            // call the delegate renderer
            JComponent component = (JComponent) fDelegate.getListCellRendererComponent(
                    list, value, index, isSelected, false);
            // make the delegate rendere non-opqaue so that the background shows through.
            this.add(component, BorderLayout.CENTER);

            return this;

        protected void paintComponent(Graphics g) {
            // if the item was selected, then paint the custom Mac selection background.
            if (fIsSelected) {
                Border backgroundPainter = fIsFocused
                        ? UIManager.getBorder("List.sourceListFocusedSelectionBackgroundPainter")
                        : UIManager.getBorder("List.sourceListSelectionBackgroundPainter");
                backgroundPainter.paintBorder(this, g, 0, 0, getWidth(), getHeight());

    public static void main(String[] args) {

        JList list = createMacSourceList();
        list.setListData(new String[]{
                "BMW", "Chevy", "Dodge", "Infiniti", "Nissan", "Porsche"});

        JScrollPane scrollPane = new JScrollPane(list);

        JFrame frame = new JFrame();

I’ve been espousing the power of Glazed Lists for a long time, and won’t be stopping any time soon! I recently needed a JList that visually grouped items into categories. GL made this super simple.

Here’s how you can create a SeparatorList, which will auto-magically insert separators into your JList for you. We’ll create a simple list of items that we want grouped by their first letter.

public class SeparatorListTest {

     * Creates a {@link Comparator} that compares the first letter of two given strings.
    private static Comparator createComparator() {
        return new Comparator() {
            public int compare(String stringOne, String stringTwo) {
                return stringOne.substring(0,1).compareTo(stringTwo.substring(0,1));

     * Creates a renderer that can render both separators and regular items.
    private static ListCellRenderer createListCellRenderer() {
        return new DefaultListCellRenderer() {
            public Component getListCellRendererComponent(
                    JList list, Object value, int index, boolean isSelected, 
                    boolean cellHasFocus) {
                // call the super renderer to take care of setting the foreground and
                // background colors.
                JLabel label = (JLabel) super.getListCellRendererComponent(
                        list, value, index, isSelected, cellHasFocus);

                // if the item being renderered is a separator, then bold it, and shift
                //    in slightly.
                // else if the item being rendered is an actual list item, make it plain
                //    and shift it in more.
                if (value instanceof SeparatorList.Separator) {
                    SeparatorList.Separator separator = (SeparatorList.Separator) value;
                } else {

                return label;

    public static void main(String[] args) {
        // create a list of items.
        EventList rawList = GlazedLists.eventListOf(
                "apple", "appricot", "acorn", "blueberry", "coconut", "chesnut", "grape");
        // create a SeparatorList based on the raw list of items using the "first-letter"
        // comparator to group them.
        SeparatorList separatorList =
                new SeparatorList(rawList, createComparator(), 0, 1000);

        JList list = new JList(new EventListModel(separatorList));
        JScrollPane scrollPane = new JScrollPane(list);

        JFrame frame = new JFrame();
        frame.add(scrollPane, BorderLayout.CENTER);

As I mentioned back here, my collegue, Jared MacDonald, also spoke at JavaOne 2009. Besides being an entertaining speaker, he delivered a great message about applying Test Driven Development (TDD) to user interface development. TDD is oft regarded as too difficult to apply in the UI space. Jared did a great job demonstrating why that’s simply not the case.

pdf Bullet Proof User Interface slides (PDF)

Until next JavaOne!


I finally got around to making the Heads Up Display (HUD) use transparency on non-Mac platforms. I wanted to keep compatibility with Java 5, so I decided to use reflection to try and gracefully use the com.sun.awt.AWTUtilities.setWindowOpaque method. Here are the two utility methods I use to make a window non-opque:

     * Try's to make the given {@link Window} non-opqaue (transparent) across 
     * platforms and JREs. This method is not guaranteed to succeed, and will fail
     * silently if the given {@code Window} cannot be made non-opaque.
     * This method is useful, for example, when creating a HUD style window that 
     * is semi-transparent, and thus doesn't want the window background to be
     * drawn.
     * @param window the {@code Window} to make non-opaque.
    public static void makeWindowNonOpaque(Window window) {
        // on the mac, simply setting the window's background color to be fully 
        // transparent makes the window non-opaque.
        window.setBackground(new Color(0, 0, 0, 0));
        // on non-mac platforms, try to use the facilities of Java 6 update 10.
        if (!PlatformUtils.isMac()) {

     * Trys to invoke {@code com.sun.awt.AWTUtilities.setWindowOpaque(window, false)} 
     * on the given {@link Window}. This will only work when running with JRE 6 update 10 
     * or higher. This method will silently fail if the method cannot be invoked.
     * @param window the {@code Window} to try and make non-opaque.
    private static void quietlyTryToMakeWindowNonOqaque(Window window) {
        try {
            Class clazz = Class.forName("com.sun.awt.AWTUtilities");
            Method method = 
                    clazz.getMethod("setWindowOpaque", java.awt.Window.class, Boolean.TYPE);
            method.invoke(clazz, window, false);
        } catch (Exception e) {
            // silently ignore this exception.

This enhancement will be part of Mac Widgets for Java 0.9.5, which will hopefully be out in the next few weeks. If you want access earlier, you can either download the code and build it from the Subversion repository, or you can email me and I’ll send you the latest jar file.

JWebPane screen shots

June 16, 2009

Alexey Ushakov has just posted screen shots of the JWebPane Java web browser that he showed in his BOF at JavaOne 2009 (which I talked about here). Below is a screen shot I pulled from Alexey’s latest blog post:
Seems like we’re getting closer!

Here are the slides for my JavaOne 2009 presentation, Simply Sweet Components, TS-4559 (read the abstract). Enjoy!

keynote Keynote version (the format I authored the presentation in)
quick_time QuickTime version (with full animations)
pdf PDF version (with notes, but no animations)

To get the most out of the presentation, I’d recommend clicking through the QuickTime version (the one with the animations), with the PDF version up on the side (which has the notes).