博为峰小博老师:
JLayeredPane面板主要是为JFC、Swing容器添加深度,它允许组件在必要的时候相互重叠。其实JLayeredPane面板将面板深度范围分成多个不同的层,将组件放入不同的层内,这样可以保证组件能够正确的重叠,而不必为具体的深度编号。
实例代码如下所示:
publicclassBWFextendsJFrameimplementsActionListener{
publicstaticintWIDTH=400;
publicstaticintHEIGHT=300;
publicstaticJLayeredPanelp;
publicstaticJButtonbutton1;
publicstaticJButtonbutton2;
publicBwfJButton() {
JFrame jf=newJFrame("博为峰教育");
jf.setSize(WIDTH,HEIGHT);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
lp=newJLayeredPane();
button1=newJButton("确定");
button2=newJButton("取消");
button1.addActionListener(this);
button2.addActionListener(this);
lp.add(button1,newInteger(200));
lp.add(button2,newInteger(300));
button1.setBounds(newRectangle(100,100,100,100));
button1.setVisible(true);
button2.setBounds(newRectangle(50,50,100,100));
button2.setVisible(true);
jf.setContentPane(lp);
jf.setVisible(true);
}
publicstaticvoidmain(String args[]){
newBwfJButton();
}
publicvoidactionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("确定")){
lp.setLayer(button1, 300);
lp.setLayer(button2, 200);
}elseif(e.getActionCommand().equals("取消")){
lp.setLayer(button1, 200);
lp.setLayer(button2, 300);
}
}
}