Wednesday, July 2, 2008

Lately I've been spending my spare time contributing code samples to the The Java Tutorial Community Portal. My hope is that one or more of these examples will be interesting enough to be included in the official tutorial. My latest addition is an example on how to override tool tip generation for a particular component. This example is a tabbed pane that shows a preview of a tab as a tooltip.

In this picture the mouse was hovering over the "images" tab.

There are techniques for installing custom universal tool tip providers. In this case I only wanted to change the behaviour for one particular component. To accomplish this I overrode the createToolTip() method of JTabbedPane with the following:

* overide createToolTip() to return a JThumbnailToolTip
public JToolTip createToolTip() {
Point loc = getMousePosition();
int index = indexAtLocation(loc.x, loc.y);

if (index != -1) {
Component comp = getComponentAt(index);

BufferedImage image = ImageFactory.toImage(comp);

JToolTip tip = new JImageToolTip(image, 0.5);

return tip;
} else {
return super.createToolTip();

This method returns an instance of JImageToolTip which displays an image of the hidden component instead of the tooltip text. The image of the component was generated by the toImage() method of my ImageFactory class.

* Generates a buffered Image of the specified component.
* @param componet
* @return image 'snapshot' of the component and it's state at the time this
* method was called.
public static BufferedImage toImage(Component componet) {
BufferedImage image = new BufferedImage(componet.getWidth(), componet
.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
graphics.fillRect(0, 0, componet.getWidth(), componet.getHeight());

return image;

The JImageToolTipThis also class was used to create a label that displays a thumbnail of an image and provides the full size image as a tooltip.

I've made the full source code available. Comments on this or any other code sample are welcomed and encouraged.

Source Code:

Collator - Faster Comparison for identical strings.

No comments: