A Thumbnail Preview Tabbed Pane

 

【转】 From:http://weblogs.java.net/blog/aberrant/archive/2008/06/a_thumbnail_pre_1.html

Posted by aberrant on June 17, 2008 at 04:07 AM

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
*/
@Override
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.setColor(componet.getBackground());
graphics.fillRect(0, 0, componet.getWidth(), componet.getHeight());
componet.paint(graphics);
graphics.dispose();

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: ThumbnailTooltipDemo-src.zip

记得以前在Let's Swing Java 的博客上也看到过一篇类似的文章,不过当时感觉他的实现方式似乎比较复杂也就没细看,aberrant的实现方式还是比较简洁的,通过短短的组件的paint方法把组件绘制到一个BufferImage中,不错。

0 评论: