Question
Is there anyway to convert a String to an ImageIcon?
Sort of like the code here: http://www.java2s.com/Code/Java/SWT-JFace-Eclipse/Createaniconinmemory.htm
Instead of the red rectangle, I would like to display a String as ImageIcon.
My intention is to display this dynamically created ImageIcon besides the Jtree nodes.
Solution
You can use the drawString
on Graphics2D
object to draw the string to a graphic. Then, its straightforward to build an ImageIcon using the Graphics2D
object. For more details on how to draw a string to graphics, look here.
OTHER TIPS
You can use a dynamic Icon, like this:
public class DynamicIcon implements Icon
{
Font font = new Font( "SansSerif", Font.PLAIN, 12 );
private final static int DEFAULT_SIZE = 16;
private int width = DEFAULT_SIZE;
private int height = DEFAULT_SIZE;
private String iconText;
public DynamicIcon( String iconText )
{
this.iconText = iconText;
recalculateIconWidth( iconText );
}
private void recalculateIconWidth( String iconText )
{
FontRenderContext frc = new FontRenderContext( null, true, true );
Rectangle2D bounds = font.getStringBounds( iconText, frc );
width = (int) bounds.getWidth();
height = (int) bounds.getHeight();
}
@Override
public int getIconHeight()
{
return height;
}
@Override
public int getIconWidth()
{
return width;
}
@Override
public void paintIcon( Component c, Graphics g, int x, int y )
{
Graphics2D g2d = (Graphics2D) g;
g2d.setFont( font );
g2d.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
g2d.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
//FontColor
g2d.setPaint( Color.BLACK );
g2d.drawString( iconText, 4, 12 );
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow