Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPanel not keeping color alpha when changing background

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.

like image 376
Cyphereion Avatar asked Dec 05 '25 10:12

Cyphereion


1 Answers

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

Example

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

like image 161
MadProgrammer Avatar answered Dec 09 '25 19:12

MadProgrammer