简体   繁体   English

Java:ImageIcon的字符串?

[英]Java: string to ImageIcon?

Is there anyway to convert a String to an ImageIcon? 反正有将String转换为ImageIcon的方法吗?

Sort of like the code here: http://www.java2s.com/Code/Java/SWT-JFace-Eclipse/Createaniconinmemory.htm 这里的代码有点像: 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. 我想将String显示为ImageIcon,而不是红色矩形。

My intention is to display this dynamically created ImageIcon besides the Jtree nodes. 我的意图是在Jtree节点之外显示此动态创建的ImageIcon。

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 );
  }
}

You can use the drawString on Graphics2D object to draw the string to a graphic. 您可以在Graphics2D对象上使用drawString将字符串绘制到图形上。 Then, its straightforward to build an ImageIcon using the Graphics2D object. 然后,使用Graphics2D对象直接构建ImageIcon即可。 For more details on how to draw a string to graphics, look here . 有关如何在图形上绘制字符串的更多详细信息,请参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM