问题
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