上篇文章大家熟悉了JPanel容器的使用,下面将通过程序实例演示它的使用方法,其代码如下:
publicclassBWF{
publicstaticintWIDTH=300;
publicstaticintHEIGHT=250;
publicstaticvoidmain(Stringargs[]){
JFramejf=newJFrame("测试JPanel");
jf.setSize(WIDTH,HEIGHT);
jf.setLayout(newBorderLayout());
//创建6个中间容器,并且将contentPane放到顶层容器内
JPanelcontentPane=newJPanel();
JPanelp1=newJPanel();
JPanelp2=newJPanel();
JPanelp3=newJPanel();
JPanelp4=newJPanel();
JPanelp5=newJPanel();
//创建9个普通按钮组件,将P1到p5个面板设置为流布局
JButtonb1=newJButton("1");
JButtonb2=newJButton("2");
JButtonb3=newJButton("3");
JButtonb4=newJButton("4");
JButtonb5=newJButton("5");
JButtonb6=newJButton("6");
JButtonb7=newJButton("7");
JButtonb8=newJButton("8");
JButtonb9=newJButton("9");
FlowLayoutf1=newFlowLayout();
FlowLayoutf2=newFlowLayout();
FlowLayoutf3=newFlowLayout();
FlowLayoutf4=newFlowLayout();
FlowLayoutf5=newFlowLayout();
p1.setLayout(f1);
p2.setLayout(f2);
p3.setLayout(f3);
p4.setLayout(f4);
p5.setLayout(f5);
//将b1,b2加到P1中,将b3,b4加到p2中
//将b5,b6加到P3中,将b7,b8加到p4中,将b9加到p5中
p1.add(b1);
p1.add(b2);
p2.add(b3);
p2.add(b4);
p3.add(b5);
p3.add(b6);
p4.add(b7);
p4.add(b8);
p5.add(b9);
contentPane.add(p1,BorderLayout.NORTH);
contentPane.add(p2,BorderLayout.SOUTH);
contentPane.add(p3,BorderLayout.EAST);
contentPane.add(p4,BorderLayout.WEST);
contentPane.add(p5,BorderLayout.CENTER);
jf.setContentPane(contentPane);
jf.setVisible(true);
}
}