GridLayout的使用:
GridLayout的类层次结构图:
java.lang.Object
--java.awt.GridLayout
GridLayout比FlowLayout多了行和列的设置,也就是说你要先设置GridLayout共有几行几列,就如同二维平面一般,然后你加进去的组件会先填第一行的格子,然后再从第二行开始填,依此类推,就像是一个个的格子一般。而且GridLayout会将所填进去组件的大小设为一样。
构造函数:GridLayout()建立一个新的GridLayout,默认值是1行1列。
GridLayout(int rows,int cols)建立一个几行几列的GridLayout.
GridLayout(int rows,int cols, int hgap,int vgap)建立一个几行几列的GridLayout,并设置组件的间距。
代码:
1
import java.awt.*;
2
import java.awt.event.*;
3
import javax.swing.*;
4
public class CardLayoutDemo implements ActionListener
{
5
JPanel p1,p2,p3,p4;
6
int i=1;
7
JFrame f;
8
public CardLayoutDemo()
{
9
f=new JFrame();//当做top-level组件
10
Container contentPane=f.getContentPane();
11
contentPane.setLayout(new GridLayout(2,1));
12
13
p1=new JPanel();
14
Button b=new Button("Change Card"); //从这里可以看出AWT中的BUTTON和SWING的JBUTTON的区别
15
b.addActionListener(this);//当按下"Change Card"时,进行事件监听,将会有系统操作产生。
16
p1.add(b); //处理操作在52-64行.
17
contentPane.add(p1);
18
19
p2=new JPanel();
20
p2.setLayout(new FlowLayout());
21
p2.add(new JButton("first"));
22
p2.add(new JButton("second"));
23
p2.add(new JButton("third"));
24
25
p3=new JPanel();
26
p3.setLayout(new GridLayout(3,1));
27
p3.add(new JButton("fourth"));
28
p3.add(new JButton("fifth"));
29
p3.add(new JButton("This is the last button"));
30
31
p4=new JPanel();
32
p4.setLayout(new CardLayout());
33
p4.add("one",p2);
34
p4.add("two",p3);
35
/**//*要显示CardLayout的卡片,除了用show(Container parent,String name)这个方法外
36
*,也可试试first(Container),next(Container),previous(Container),last(Container)这
37
*四个方法,一样可以达到显示效果。
38
*/
39
((CardLayout)p4.getLayout()).show(p4,"one");
40
41
contentPane.add(p4);
42
43
f.setTitle("CardLayout");
44
f.pack();
45
f.setVisible(true);
46
47
f.addWindowListener(
48
new WindowAdapter()
{
49
public void windowClosing(WindowEvent e)
{
50
System.exit(0);
51
}
52
}
53
);
54
55
}
56
public void actionPerformed(ActionEvent event)
{
57
switch(i)
{
58
case 1:
59
((CardLayout)p4.getLayout()).show(p4,"two");
60
break;
61
case 2:
62
((CardLayout)p4.getLayout()).show(p4,"one");
63
break;
64
}
65
i++;
66
if (i==3) i=1;
67
f.validate();
68
}
69
public static void main(String[] args)
{
70
new CardLayoutDemo();
71
}
72
}
73
地震让大伙知道:居安思危,才是生存之道。
posted on 2007-03-03 10:27
小寻 阅读(276)
评论(0) 编辑 收藏 所属分类:
j2se/j2ee/j2me