JPanel在更改背景时不保持颜色alpha [英] JPanel not keeping color alpha when changing background

查看:286
本文介绍了JPanel在更改背景时不保持颜色alpha的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jpanel的背景色会变得比以前更加不透明。值得注意的是我正在使用jpanel的setBackground方法。以下是您可能希望查看的代码的一些链接。



以获取更多详细信息


Ever so slowly the jpanel's background color will become more opaque than it previously was. Notable I am using the setBackground method of the jpanel. Here are a few links to code you might want to look at.

Custom GUI Button

The Gui it's in -- Look at line 158.

解决方案

Two things popout

  1. Swing doesn't support alpha based colors, either a Swing component is opaque or transparent. You have to fake it, by making the component transparent and then override paintComponent and use a AlphaCompositeto fill it, otherwise Swing won't know it should be painting under you component and you'll end up wi a bunch more paint issues
  2. In your TranslucentPanel, you're allowing the component to paint its background and then fill it again with a translucent versions of it, doubling up. You need to set this component to transparent

The first thing I would do is change the TranslucentPane so you can control the transparency level, for example

public class TranslucentPane extends JPanel {

    private float alpha = 1f;

    public TranslucentPane() {
    }

    public void setAlpha(float value) {
        if (alpha != value) {
            alpha = Math.min(Math.max(0f, value), 1f);
            setOpaque(alpha == 1.0f);
            repaint();
        }
    }

    public float getAlpha() {
        return alpha
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g); 

        Graphics2D g2d = (Graphics2D) g.create();
        g2d.setComposite(AlphaComposite.SrcOver.derive(getAlpha()));
        g2d.setColor(getBackground());
        g2d.fillRect(0, 0, getWidth(), getHeight());
        g2d.dispose();

    }

}

Next, I would change panel_Bottom to actually use it...

private TranslucentPane panel_Bottom;

//...

panel_Bottom = new TranslucentPane();
panel_Bottom.setBorder(new LineBorder(new Color(0, 0, 0)));
if(isTransparent){
    panel_Bottom.setAlpha(0.85f);
}

I would also, HIGHLY, recommend that you stop using null layouts and learn how to use appropriate layout managers, they will make your life simpler

Have a look at Laying Out Components Within a Container for more details

这篇关于JPanel在更改背景时不保持颜色alpha的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆