这是我在csdn写的第一篇博客,本人本人比较懒,即使有一些新的东西想写出来,到最后还是不了了之。这篇博客算是一个新的开始吧!
setOpaque(true/false);看看API文档是怎么说的:
“if true the component paints every pixel within its bounds.
Otherwise, the component may not paint some or all of its pixels, allowing the underlying pixels to show through.”。
即如果设置为true的话,原样显示组件中的每个像素,也就是正常显示;这里主要讲解设置为false时。
当设置为false时,组件并未不会显示其中的某些像素,允许控件下面的像素显现出来。
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mainclass;
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainClass extends JFrame {
public MainClass() {
super("Opaque JPanel Demo");
setSize(400, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
<span style="background-color: rgb(204, 204, 204);"> JPanel opaque = createNested(true);
JPanel notOpaque = createNested(false);</span>
getContentPane().setLayout(new FlowLayout());
getContentPane().add(opaque);
getContentPane().add(notOpaque);
}
public static void main(String[] args) {
MainClass oe = new MainClass();
oe.setVisible(true);
}
public JPanel createNested(boolean opaque) {
JPanel outer = new JPanel(new FlowLayout());
JPanel inner = new JPanel(new FlowLayout());
<span style="background-color: rgb(192, 192, 192);"> outer.setBackground(Color.BLUE);
inner.setBackground(Color.red);</span>
inner.setOpaque(opaque);
inner.setBorder(BorderFactory.createLineBorder(Color.gray));
inner.add(new JButton("Button"));
outer.add(inner);
return outer;
}
}
运行结果如图:
如图,第一个panel中inner设置setOpaque(true),则inner区域中的背景色红色就会遮挡住外层组件中的蓝色;而在第二个panel中,由于inner设置为setOpaque(false),则inner区域中的背景色就是透明的了,因此就显示为外围组件outer的颜色蓝色。