After using custom made color:
Color bg = new Color(0f,0f,0f,0.5f);
for a JTextPane
background I can see that background of JTextPane
is shown with parts of background that comes from Jlabel
that includes JTextPane
in it.
Picture of what's happening:
So the bottom part of JTextPane
background is OK, but the top one that's behind a text is having some issues.
How can I fix it? Have I made mistake by using custom color for simple transparent background for JTextPane
?
Code for this part of the program:
t = new JTextPane();
SimpleAttributeSet style = new SimpleAttributeSet();
StyleConstants.setAlignment(style , StyleConstants.ALIGN_CENTER);
StyleConstants.setForeground(style , Color.white);
StyleConstants.setFontFamily(style, "Times new Roman");
StyleConstants.setFontSize(style, 20);
StyleConstants.setBold(style, true);
t.setParagraphAttributes(style,true);
t.setText(" " + text.getT1().get(0).toUpperCase());
t.setOpaque(true);
Color bg = new Color(0f,0f,0f,0.5f);
t.setBackground(bg);
t.setEditable(false);
t.setBounds(250, 400, 300, 50);
animation.add(t);
Swing doesn't support transparent backgrounds properly. Swing expects the component to be fully opaque or not based on the setOpaque(....) property.
When using transparent background you need to make sure the background of the parent container is painted first before the background of the transparent component is painted.
Check out Background With Transparency for more information on this process.
You can customize you component and do your own painting with code like:
JPanel panel = new JPanel()
{
protected void paintComponent(Graphics g)
{
g.setColor( getBackground() );
g.fillRect(0, 0, getWidth(), getHeight());
super.paintComponent(g);
}
};
panel.setOpaque(false); // background of parent will be painted first
panel.setBackground( new Color(255, 0, 0, 20) );
frame.add(panel);
Or the easier approach is to use the AlphaContainer
class provided in the above link.