使用JTextPane背景颜色的自定义颜色的工件显示

0 java swing jtextpane

使用定制颜色后:

Color bg = new Color(0f,0f,0f,0.5f);
Run Code Online (Sandbox Code Playgroud)

对于JTextPane背景我可以看到背景JTextPane显示的背景部分Jlabel包括JTextPane在其中.

发生了什么:

问题的形象

所以JTextPane背景的底部部分是可以的,但是文本背后的顶部部分有一些问题.

我该如何解决?我是否因使用自定义颜色的简单透明背景而犯了错误JTextPane

该部分计划的代码:

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);
Run Code Online (Sandbox Code Playgroud)

cam*_*ckr 5

Swing不能正确支持透明背景.Swing期望组件完全不透明或不基于setOpaque(....)属性.

使用透明背景时,您需要确保在绘制透明组件的背景之前首先绘制父容器的背景.

有关此过程的更多信息,请查看背景透明度.

您可以自定义组件并使用以下代码进行绘制:

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);
Run Code Online (Sandbox Code Playgroud)

或者更简单的方法是使用AlphaContainer上面链接中提供的类.