2

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);
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Dim
  • 4,527
  • 15
  • 80
  • 139

2 Answers2

3

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();
nIcE cOw
  • 24,468
  • 7
  • 50
  • 143
Azad
  • 5,047
  • 20
  • 38
3

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.

tbodt
  • 16,609
  • 6
  • 58
  • 83