2

当我使用具有 alpha 值的前景色的 JLabel 时,如下所示:

JLabel label = new JLabel( "This is non HTML text with correct alpha color" );
label.setForeground( new Color( 1.0f, 1.0f, 1.0f, 0.5f) );

标签以 0.5-alpha 正确显示,因此为 50% 灰色。

但是当我将文本更改为 HTML 时(以更好地控制文本呈现),如下所示:

JLabel label = new JLabel( "<html><p>This is HTML text with incorrect alpha color</p></html>" );
label.setForeground( new Color( 1.0f, 1.0f, 1.0f, 0.5f) );

然后标签是 100% 白色。看起来,在渲染 HTML 时,前景色的 alpha 值只是被忽略了。

我在 Windows 7 64 位下使用 Java 1.6.0_26(32 位)。

这是一个错误还是一个已知的限制,或者我在这里有什么问题吗?

4

2 回答 2

2

您不能将 HTML 代码和 setForeground 样式混合在一起。

请参阅Oracle 的JLabel html text ignores setFont和 How to use JLabels( 1 ) 教程。

只需使用 HTML 或 JLabel 样式。

于 2012-09-30T17:27:42.160 回答
1

为了给我自己的问题一个可能的答案,我刚刚找到了一种通过 HTML 渲染实现 alpha 透明度的方法。只需覆盖 JLabel 的“paintComponent”方法并使用带有给定 Graphics2D 实例的 AlphaComposite:

@Override
protected void paintComponent( Graphics g )
{
    Composite alphaComposite = AlphaComposite.getInstance( AlphaComposite.SRC_OVER, 0.5f );

    Graphics2D g2d = (Graphics2D)g.create();
    g2d.setComposite( alphaComposite );

    super.paintComponent( g2d );
}
于 2012-09-30T21:14:33.427 回答