博为峰小博老师:
JLayeredPane面板主要是为JFC、Swing容器添加深度,它允许组件在必要的时候相互重叠。其实JLayeredPane面板将面板深度范围分成多个不同的层,将组件放入不同的层内,这样可以保证组件能够正确的重叠,而不必为具体的深度编号。
实例代码如下所示:
public class BWF extends JFrame implements ActionListener{
public static int WIDTH=400;
public static int HEIGHT=300;
public static JLayeredPane lp;
public static JButton button1;
public static JButton button2;
public BwfJButton() {
JFrame jf=new JFrame("博为峰教育");
jf.setSize(WIDTH, HEIGHT);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
lp=new JLayeredPane();
button1=new JButton("确定");
button2=new JButton("取消");
button1.addActionListener(this);
button2.addActionListener(this);
lp.add(button1,new Integer(200));
lp.add(button2,new Integer(300));
button1.setBounds(new Rectangle(100,100,100,100));
button1.setVisible(true);
button2.setBounds(new Rectangle(50,50,100,100));
button2.setVisible(true);
jf.setContentPane(lp);
jf.setVisible(true);
}
public static void main(String args[]){
new BwfJButton();
}
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("确定")){
lp.setLayer(button1, 300);
lp.setLayer(button2, 200);
}else if(e.getActionCommand().equals("取消")){
lp.setLayer(button1, 200);
lp.setLayer(button2, 300);
}
}
}