流式布局flowlayout,可以通过传参,来制定布局对齐方式和组件水平和垂直的像素值。
jp.setLayout( new FlowLayout(FlowLayout.LEFT) );
边界布局borderlayouT包括5个区域,North south east west center等,注意其构造方法。和为各个块添加控件。窗口大小改变时 只有center区域变化。
add("North", new JButton("North"));//为布局添加控件
add("South", new JButton("South"));
add("East", new JButton("East"));
add("West", new JButton("West"));
add("Center", new JButton("Center"));
网格布局,各控件相对位置不变,各组件宽度高度相同。
setLayout(new GridLayout(3,2));
setFont(new Font("Helvetica", Font.PLAIN, 14));
add(new JButton("Button 1"));.....
卡片布局,就像选牌一样(这些牌都有共享同一区域)注意Applet的用法。
import java.applet.*; import java.awt.Button; import java.awt.CardLayout; import java.awt.Choice; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.LayoutManager; import java.awt.Panel; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class CardDemo extends Applet implements ActionListener{ Panel p0,p1,p2,p3; Choice c1,c2;//下拉列表 Button b1,b2,b3,b4; TextField t1,t2; public void init(){ p1=new myPanel1(new Color(0).pink,new FlowLayout(),100,100); //p1 = new myPanel(new Color(0).red, new FlowLayout(), 100, 100); Choice c1=new Choice(); c1.addItem("option1"); c1.addItem("option2"); p1.add(c1); p2=new myPanel1(new Color(0).blue,new FlowLayout(),100,100); //p1 = new myPanel(new Color(0).red, new FlowLayout(), 100, 100); Choice c2=new Choice(); c2.addItem("option1"); c2.addItem("option2"); p2.add(c2); p3=new myPanel1(new Color(0).cyan,new FlowLayout(),100,100); //p1 = new myPanel(new Color(0).red, new FlowLayout(), 100, 100); Choice c3=new Choice(); c3.addItem("option1"); c3.addItem("option2"); p3.add(c1); p0=new myPanel1(new Color(0).white, new CardLayout(0,0), 100, 100); setLayout(new FlowLayout()); add(p0); p0.add("first card",p1); p0.add("second card",p2); p0.add("third card",p3); add(b1=new Button("card1")); add(b2=new Button("card2")); add(b3=new Button("card3")); add(b4= new Button("你选了哪一个?")); add(t2=new TextField()); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); } public void actionPerformed(ActionEvent e) { if(e.getSource()==b1){ ((CardLayout)p0.getLayout()).show(p0, "first card"); } else if(e.getSource()==b2){ ((CardLayout)p0.getLayout()).show(p0, "second card"); } else if(e.getSource()==b3){ ((CardLayout)p0.getLayout()).show(p0, "third card"); } else if(e.getSource()==b4){ Component c[]=p0.getComponents(); int i=0; int j=c.length; while(i<j){ if (c[i].isVisible()){ t2.setText(" "+(i+1)); break; }else{ i++; } } } } } class myPanel1 extends Panel { int w; int h; public myPanel1(Color color,LayoutManager layoutManager,int width,int height) { super();//调用父类工作方法。 w=width; h=height; setBackground(color); setLayout(layoutManager); } public Dimension getMinimumSize(){ return new Dimension(w,h); } public Dimension getpreferredSize() { return new Dimension(w,h); } }
多练习一下。