Question

I have custom class in Java that extends JButton and have an image background. I can set alpha with this function in the class:

@Override
public void paint(Graphics g) 
{       
    Graphics2D g2 = (Graphics2D) g.create();
    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, (float) 0.5));
    super.paint(g2);
    g2.dispose();
}

How can set getter and setter to this function so I can control the opacity from the class that creates the button? I need something like this:

MyJButton myJbtn = new MyJButton();
myJbtn.setOpacity(0.5);
Was it helpful?

Solution

Create an instance field opacity in your button class, then create setter and getters:

private float opacity;
//......
public setOpacity(float opacity) {
    this.opacity = opacity;
}

public void getOpacity(){
    return this.opacity
}

Then class repaint after setting any opacity to the button:

MyJButton myJbtn = new MyJButton();
myJbtn.setOpacity(0.5);
myJbtn.repaint();

OTHER TIPS

The setOpacity method can be implemented like this:

public void setOpacity(float opacity) {
    this.opacity = opacity;
    repaint();
}

opacity is an instance field that stores the current opacity. It is used by paint for the opacity value.

You may also want a getOpacity method, which is not strictly required.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top