Showing an Image in a ToolTip
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JToolTip;
import javax.swing.SwingUtilities;
import javax.swing.plaf.metal.MetalToolTipUI;
public class Main {
public static void main(String[] argv) {
JLabel wonLabel = new JLabel() {
public JToolTip createToolTip() {
return new ImageToolTip();
}
};
wonLabel.setToolTipText("asdf");
}
}
class ImageToolTip extends JToolTip {
public ImageToolTip() {
setUI(new ImageToolTipUI());
}
}
class ImageToolTipUI extends MetalToolTipUI {
public void paint(Graphics g, JComponent c) {
FontMetrics metrics = c.getFontMetrics(g.getFont());
g.setColor(c.getForeground());
g.drawString(((JToolTip) c).getTipText(), 1, 1);
g.drawImage(new ImageIcon("yourImage").getImage(), 1, metrics.getHeight(), c);
}
public Dimension getPreferredSize(JComponent c) {
FontMetrics metrics = c.getFontMetrics(c.getFont());
String tipText = ((JToolTip) c).getTipText();
if (tipText == null) {
tipText = "";
}
Image image = new ImageIcon("yourImage").getImage();
int width = SwingUtilities.computeStringWidth(metrics, tipText);
int height = metrics.getHeight() + image.getHeight(c);
if (width < image.getWidth(c)) {
width = image.getWidth(c);
}
return new Dimension(width, height);
}
}
Related examples in the same category