Sunday, November 3, 2013

Transparent JButton, JLabel...J-anything you want

When I was doing my 2nd year project I wanted to transparent a jpanel and several buttons. After searching and reading several posts I founded a way to do it easier. Using this you can transparent most of swing controls. To do this is very easy. you just need to rewrite the class that you want to transparent with adding alpha value. 

public class TransparentButton extends JButton{
     static float value = 1.0f;
    public TransparentButton(float t) {
        super();
        value=t;
        setOpaque(false); 
    }

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

Here you can see I have extended the JButton class and creating another jbutton called TransparentButton. "value" is the alpha value. After I implemented a constructor to pass that alpha value. So I can use that when I'm creating the button. It's not a must to declare the value variable as static. Finally override the paint method and add your alpha value. 

Now you have to do is run this constructor when you're creating a button. I'll show you how to do it in Netbeans.

First drag and drop the button you want to transparent. I'll add two buttons and I'm going to transparent the right button.





Then right click on that button and from the list choose Customize Code... 

In the code customizer window you can see the constructor of button is there. Now we have to change that constructor and run our constructor there. To change that, from the drop down menu select custom creation.



Then you can edit the constructor. Delete the Jbutton constructor and run the TransparentButton's constructor with passing the alpha value.




Now save the project and run. Tadaa !!!



Like this you can extend most of the swing controls like Jlabel, JToggleButton, JPanel, ... etc.  
You can download a sample project by clicking the link below. 

TransparentTuteAnjula GitHub Project




1 comment: