【问题标题】:Java JLabel ignores alpha value of foreground color when rendering HTMLJava JLabel 在渲染 HTML 时忽略前景色的 alpha 值
【发布时间】:2012-10-01 05:14:33
【问题描述】:

当我使用具有 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 位)。

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

【问题讨论】:

  • 不透明度(alpha)真的适用于 html 代码吗?看看stackoverflow.com/questions/1531494/…
  • 我认为你是对的,我只知道 CSS 的 alpha 透明度,而不是“普通”HTML。

标签: java html jlabel alpha


【解决方案1】:

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

请参阅 oracle 中的 JLabel html text ignores setFont 和如何使用 JLabels(1) 教程。

只需使用 HTML 或 JLabel 样式。

【讨论】:

  • 好的,非常感谢您的回答。作为旁注,如果我不能混合它,它应该完全忽略前景色,而不仅仅是 alpha 部分。我的意思是,我可以用“.setForeground(Color.GREEN);”将 HTML 文本变为绿色,到 setForeground-Styling 仍然对 HTML 呈现有影响
【解决方案2】:

为了给我自己的问题一个可能的答案,我刚刚找到了一种通过 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 );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-11
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    • 2012-08-25
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多