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);
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();
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.