gpt4 book ai didi

Java:字符串到 ImageIcon?

转载 作者:行者123 更新时间:2023-12-02 00:44:20 26 4
gpt4 key购买 nike

是否有办法将字符串转换为 ImageIcon?

有点像这里的代码:http://www.java2s.com/Code/Java/SWT-JFace-Eclipse/Createaniconinmemory.htm

我想将字符串显示为 ImageIcon,而不是红色矩形。

我的目的是在 Jtree 节点之外显示这个动态创建的 ImageIcon。

最佳答案

您可以使用动态图标,如下所示:

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

关于Java:字符串到 ImageIcon?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9309623/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com