无法正确理解代码

问题描述:

在下面的代码中,我无法理解setBackground()方法为哪个图层设置背景。其次,当我包括这一行为什么在窗口中有一个洞,意味着当我在窗口之间点击时,它最小化,因为我已经点击了其他地方。无法正确理解代码

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

} 

未叫特定对象上的所有方法,实际上是呼吁this,所以

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

就像

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

这意味着它是呼吁JFrame

+0

然后JFrame中应该有变成透明的,但内容窗格仍然不透明。就像contentPane()是jframe的一部分,因此设置jframe透明使所有3内容窗格,玻璃窗格和Layered窗格透明。 – 2012-08-08 10:57:56

+0

@Naveen尝试将内容窗格设置为透明,最简单的方法是创建一个JPanel,在面板上调用setOpaque(false),然后调用JFrame的setContentPane,传入面板 – MadProgrammer 2012-08-08 11:07:08

+0

@MadProgrammer使用此方法将使内容窗格透明,但JFrame仍然不透明,因此它不起作用。 – 2012-08-08 11:14:49

另外一个问题,你会发现,是设置了框的opacity会影响它的所有的孩子同样

如果你想看到一个不错的长期讨论(&例子)看到how to set JFrame background transparent but JPanel or JLabel Background opaque?

+0

Thanx for the link.Taught伟大的新概念 – 2012-08-08 11:19:50

+0

漂亮的图片+1 – mKorbel 2012-08-08 11:37:19