Java JLabel ignores alpha value of foreground color when rendering HTML

怎甘沉沦 提交于 2019-12-06 10:53:29

问题


When I use a JLabel with a foreground color which has an alpha value, like so:

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

the label is displayed correctly with 0.5-alpha, so 50% gray.

But when I change the text to HTML (to have more control over the text rendering), like so:

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

Then the label is 100% white. It seems, while rendering HTML, the alpha value of the foreground color is just being ignored.

I'm using Java 1.6.0_26 (32bit) under Windows 7 64 Bit.

Is this a bug or a known limitation, or do I anything wrong here?


回答1:


You cannot mix HTML code and setForeground styling together.

See JLabel html text ignores setFont and How to use JLabels(1) tutorial from oracle.

Just use either HTML or JLabel styling.




回答2:


To give a possible answer to my own question, I just found a way to do alpha transparency with HTML-rendering. Just override the "paintComponent" Method of JLabel and use an AlphaComposite with the given Graphics2D instance:

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


来源:https://stackoverflow.com/questions/12663268/java-jlabel-ignores-alpha-value-of-foreground-color-when-rendering-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!