Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Ok so this was a problem I stumbled upon when I wanted to use transparency..

So the code for changing background on hover is this...

 received.setMouseListener(new MouseAdapter()
 @Override 
 public void mouseEntered(MouseEvent me) 
 {
        received.setBackground(new Color(50,50,50,100));
 } 
});

At the beginning I set the blue color for the button..

Here's the gif showing the color changes...

GifMeme09541718022016.gif https://drive.google.com/file/d/0B9XFyaTVy8oYci1zMmRhMmtYcnM/view?usp=docslist_api

Why does this happen? If this is not a correct approach what is the correct approach?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
305 views
Welcome To Ask or Share your Answers For Others

1 Answer

Basically, Swing only understand how to paint transparent and opaque components, it doesn't know how to deal with translucent components, so using an alpha based background color causes issues.

Instead, you need to "fake" it by taking control over how the component's background is painted, for example...

Alpha based hover

public class FakeTransperencyButton extends JButton {

    private float alpha = 0;

    public FakeTransperencyButton(String text) {
        super(text);
        setOpaque(false);
        setBackground(Color.RED);

        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                alpha = 0.4f;
                repaint();
            }

            @Override
            public void mouseExited(MouseEvent e) {
                alpha = 0f;
                repaint();
            }

        });
    }

    @Override
    public boolean isOpaque() {
        return false;
    }

    public float getAlpha() {
        return alpha;
    }

    protected void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.setComposite(AlphaComposite.SrcOver.derive(getAlpha()));
        g2d.setColor(getBackground());
        g2d.fillRect(0, 0, getWidth(), getHeight());
        g2d.dispose();
        super.paintComponent(g);
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...