Below is the code which i’m using to make the content pane transparent.What i don’t understand is if i comment out the line “setBackground(new Color(0,0,0,0)); ” my window is just painted with the gradient color and its opaque .However using the above line of code makes it transparent.
Can anyone tell what is the relation between this “setBackground(new Color(0,0,0,0)); ” and the gradient color which i’m setting for JPanel.
Thanx in advance.
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.GraphicsDevice.WindowTranslucency;
import java.awt.GraphicsEnvironment;
import java.awt.Paint;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class transparent extends JFrame {
public transparent() {
super("Transparent Window");
setBackground(new Color(0,0,0,0));//problem with this line
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,200);
getContentPane().setLayout(new FlowLayout());
JPanel jp=new JPanel(){
public void paintComponent(Graphics g)
{
//super.paintComponent(g);
Graphics2D g2=(Graphics2D)g;
Paint gp=new GradientPaint(300, 700, new Color(20,20,210,0), 100, 00, new Color(10,20,40,255));
g2.setPaint(gp);
g2.fillRect(0, 0, getWidth(),getHeight());
}
};
setContentPane(jp);
JButton jbtn=new JButton("Enter");
add(jbtn);
setVisible(true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame.setDefaultLookAndFeelDecorated(true);
SwingUtilities.invokeLater(new Runnable(){public void run(){new transparent();}});
}
}
The color (0,0,0,0) is fully transparent, as is any color with a alpha-component (fourth parameter in the Color-contructor) set to zero.
http://docs.oracle.com/javase/7/docs/api/java/awt/Color.html#Color(int, int, int, int)
http://en.wikipedia.org/wiki/Alpha_compositing
When you set this as your background, the frame will become transparent! This is crucial, because if your frame is not transparent, having a transparent panel on top will only let you see through this panel and onto the underlying frame. Making the frame transparent as well let’s you see through to whatever lies behind.