天天看點

博為峰Java技術文章 ——JavaSE Swing JPanel III

博為峰小博老師:

上篇文章程式執行個體中,建立了6個面闆容器類,分别是contentPane、p1、p2、p3、p4、 p5,其中contentPane是與頂層視窗關聯的内容面闆,其餘5個面闆容器則是與布管理器中每個部分相關聯的面闆。上篇文章程式代碼使用的是不帶參數的Panel容器類構造器,下面使用帶參數的Panel容器類構造器來重新編寫上例的程式代碼。其代碼如下所示:

public class BWF{

public static int WIDTH=300;

public static int HEIGHT=250;

public static void main(String args[]){

JFrame jf=new JFrame("測試JPanel");

jf.setSize(WIDTH, HEIGHT);

jf.setLayout(new BorderLayout());

//建立6個中間容器,并且将contentPane放到頂層容器内

JPanel contentPane=new JPanel();

JPanel p1=new JPanel();

JPanel p2=new JPanel();

JPanel p3=new JPanel();

JPanel p4=new JPanel();

JPanel p5=new JPanel();

//建立9個普通按鈕元件,将P1到p5個面闆設定為流布局

JButton b1=new JButton("1");

JButton b2=new JButton("2");

JButton b3=new JButton("3");

JButton b4=new JButton("4");

JButton b5=new JButton("5");

JButton b6=new JButton("6");

JButton b7=new JButton("7");

JButton b8=new JButton("8");

JButton b9=new JButton("9");

p1.setLayout(new FlowLayout());

p2.setLayout(new FlowLayout());

p3.setLayout(new FlowLayout());

p4.setLayout(new FlowLayout());

p5.setLayout(new FlowLayout());

//将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);

}

}

博為峰Java技術文章 ——JavaSE Swing JPanel III