1 /* 2 * This file is an adapted example from javareference.com 3 * for more information visit, 4 * http://www.javareference.com 5 */ 6 package com.hammurapi.jcapture; 7 8 import java.awt.Dimension; 9 import java.awt.FontMetrics; 10 import java.awt.Graphics; 11 import java.awt.Image; 12 13 import javax.swing.JComponent; 14 import javax.swing.JToolTip; 15 import javax.swing.SwingUtilities; 16 import javax.swing.plaf.metal.MetalToolTipUI; 17 18 /** 19 * This class extends JToolTip and set the UI to ImageToolTipUI. 20 * 21 * @author Rahul Sapkal(rahul@javareference.com) 22 */ 23 public class ImageToolTip extends JToolTip { 24 25 /** 26 * This class extends MetalToolTipUI and provides customizes it to draw a 27 * given image on it. 28 * 29 * @author Rahul Sapkal(rahul@javareference.com) 30 */ 31 private class ImageToolTipUI extends MetalToolTipUI { 32 private Image m_image; 33 ImageToolTipUI(Image image)34 public ImageToolTipUI(Image image) { 35 m_image = image; 36 } 37 38 /** 39 * This method is overriden from the MetalToolTipUI to draw the given 40 * image and text 41 */ paint(Graphics g, JComponent c)42 public void paint(Graphics g, JComponent c) { 43 FontMetrics metrics = c.getFontMetrics(g.getFont()); 44 g.setColor(c.getForeground()); 45 46 g.drawString(((ImageToolTip) c).text, 3, 15); 47 48 g.drawImage(m_image, 3, metrics.getHeight() + 3, c); 49 } 50 51 /** 52 * This method is overriden from the MetalToolTipUI to return the 53 * appropiate preferred size to size the ToolTip to show both the text 54 * and image. 55 */ getPreferredSize(JComponent c)56 public Dimension getPreferredSize(JComponent c) { 57 FontMetrics metrics = c.getFontMetrics(c.getFont()); 58 String tipText = ((JToolTip) c).getTipText(); 59 if (tipText == null) { 60 tipText = ""; 61 } 62 63 int width = SwingUtilities.computeStringWidth(metrics, tipText); 64 int height = metrics.getHeight() + m_image.getHeight(c) + 6; 65 66 if (width < m_image.getWidth(c)) { 67 width = m_image.getWidth(c); 68 } 69 70 return new Dimension(width, height); 71 } 72 } 73 74 private String text; 75 ImageToolTip(String text, Image image)76 public ImageToolTip(String text, Image image) { 77 this.text = text; 78 setUI(new ImageToolTipUI(image)); 79 } 80 } 81