博為峰小博老師:
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);
}
}
}