1

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();}});
}

}
sunil
  • 6,444
  • 1
  • 32
  • 44
Naveen
  • 7,944
  • 12
  • 78
  • 165

2 Answers2

2

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.

MByD
  • 135,866
  • 28
  • 264
  • 277
  • Then the JFrame should have become transparent but the content pane is still opaque.Is it like contentPane() is a part of jframe so setting jframe transparent makes all the 3-content pane,glass pane and Layered pane transparent.? – Naveen Aug 08 '12 at 10:57
  • @Naveen Try setting the content pane transparent, the easiest way would be to create a JPanel, calling setOpaque(false) on the panel then calling JFrame's setContentPane, passing in the panel – MadProgrammer Aug 08 '12 at 11:07
  • @MadProgrammer Using this method will make the content pane transparent but the JFrame is still opaque hence it will have no effect. – Naveen Aug 08 '12 at 11:14
  • @Naveen, sorry, you should also set the frame to undecorated – MadProgrammer Aug 08 '12 at 15:40
2

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?

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366