Question

In the following code, i cannot understand setBackground() methods sets the background for which layer. Secondly, when i include this line why there becomes a hole in the window, means when i click in between the window, it minimizes as i have clicked somewhere else.

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
java.awt.GraphicsDevice;
import java.awt.GraphicsDevice.WindowTranslucency;
import java.awt.GraphicsEnvironment;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;


public class transparentWindow extends JFrame {

public transparentWindow() {
    // TODO Auto-generated constructor stub
    //JFrame jfrm=new JFrame("Transparent Window");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(300,200);
    getContentPane().setLayout(new FlowLayout());
    //setBackground(new Color(0,0,0,0));

    add(new JButton("Enter"));
    setOpacity(0.7f);
    setVisible(true);
}
public static void main(String[] args) {
    // TODO Auto-generated method stub
    GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice gd=ge.getDefaultScreenDevice();
    if(!gd.isWindowTranslucencySupported(WindowTranslucency.TRANSLUCENT))
    {
        System.out.println("Transparency not supported");
        System.exit(0);
    }
    JFrame.setDefaultLookAndFeelDecorated(true);
    SwingUtilities.invokeLater(new Runnable(){public void run(){new transparentWindow();}});
}

}
Was it helpful?

Solution

All methods that are not called on a specific object, are actually called on this, so

setBackground(new Color(0,0,0,0));

is just like

this.setBackground(new Color(0,0,0,0));

Which means that it is called on the JFrame.

OTHER TIPS

The other issue you will find, is that setting the frame's opacity will effect all it's children equally

If you want to see a nice long discussion (& example) see how to set JFrame background transparent but JPanel or JLabel Background opaque?

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