Custom Java tool tip with Swing components as content does not show up

Tool tips can render HTML. If you can form URLs to the images (not practical if they are generated in memory but usually doable otherwise), it is an easy matter to write some HTML that will load the images, and use that HTML as the tool tip.


E.G.

MultiIconToolTip

import javax.swing.*;

class MultiIconToolTip {

    public static void main(String[] args) throws Exception {
        final String html =
            "<html><body>" +
            "<img src='" +
            "http://i.stack.imgur.com/OVOg3.jpg" +
            "' width=160 height=120> " +
            "<img src='" +
            "http://i.stack.imgur.com/lxthA.jpg" +
            "' width=160 height=120>" +
            "<p>Look Ma, no hands!";
        SwingUtilities.invokeLater( new Runnable() {
            public void run() {
                JLabel hover = new JLabel("Point at me!");
                hover.setToolTipText(html);
                JOptionPane.showMessageDialog(null, hover);
            }
        });
    }
}

It might sound silly but, have you tried setting bounds for JPanel ?

setBounds(100, 100, 150, 50);

And you can try setting a gap between components in BorderLayout

JPanel content = new JPanel(new BorderLayout(1,1));

The base "problems" are that JToolTip

  • is-not designed as a container, it's only accidentally a container because JComponent is. For a Swing "not-container" its the responsibility of the ui-delegate to act as LayoutManager.
  • isn't rich enough, it can handle text-only (at least with the emergency door html, which is @Andrew's favourite :-)

By-passing those limitations basically is a driving that widget nearly over the edge. A clean solution would roll a new component .. On the other hand, the OP already found the screws to tweak. The only thingy that could be slightly improved is to neither call setXXSize, nor set a custom ui. Instead, make it behave like a container by overriding getXXSize() like:

@Override
public Dimension getPreferredSize() {
    if (getLayout() != null) {
        return getLayout().preferredLayoutSize(this);
    }
    return super.getPreferredSize();
}

I'd suggest to using JWindow or un_decorated JDialog, as popup window (used by default for JCalendar or JDatePicker) rather than JTooltip, for nicer output to the GUI implements Translucent and Shaped Windows


NOTE: If you use JDK 1.6 or older, use this method instead. It only works with SUN JDK.