2

String を ImageIcon に変換する方法はありますか?

ここのコードのようなもの: http://www.java2s.com/Code/Java/SWT-JFace-Eclipse/Createaniconinmemory.htm

赤い四角形の代わりに、文字列を ImageIcon として表示したいと思います。

私の意図は、この動的に作成された ImageIcon を Jtree ノードのほかに表示することです。

4

2 に答える 2

6

次のように、動的なアイコンを使用できます。

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 );
  }
}
于 2012-02-16T14:17:34.527 に答える
2
于 2012-02-16T10:36:17.253 に答える