大家好,又见面了,我是你们的朋友全栈君。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,并设置组件的间距。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutDemo implements ActionListener {
JPanel p1, p2, p3, p4;
int i = 1;
JFrame f;
public CardLayoutDemo() {
f = new JFrame();// 当做top-level组件
Container contentPane = f.getContentPane();
contentPane.setLayout(new GridLayout(2, 1));
p1 = new JPanel();
Button b = new Button("Change Card");
b.addActionListener(this);// 当按下"Change Card"时,进行事件监听,将会有系统操作产生。
p1.add(b); // 处理操作在52-64行.
contentPane.add(p1);
p2 = new JPanel();
p2.setLayout(new FlowLayout());
p2.add(new JButton("first"));
p2.add(new JButton("second"));
p2.add(new JButton("third"));
p3 = new JPanel();
p3.setLayout(new GridLayout(3, 1));
p3.add(new JButton("fourth"));
p3.add(new JButton("fifth"));
p3.add(new JButton("This is the last button"));
p4 = new JPanel();
p4.setLayout(new CardLayout());
p4.add("one", p2);
p4.add("two", p3);
/* * 要显示CardLayout的卡片,除了用show(Container parent,String name)这个方法外 * ,也可试试first( * Container),next(Container),previous(Container),last(Container)这 * 四个方法,一样可以达到显示效果。 */
((CardLayout) p4.getLayout()).show(p4, "one");
contentPane.add(p4);
f.setTitle("CardLayout");
f.pack();
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent event) {
switch (i) {
case 1:
((CardLayout) p4.getLayout()).show(p4, "two");
break;
case 2:
((CardLayout) p4.getLayout()).show(p4, "one");
break;
}
i++;
if (i == 3)
i = 1;
f.validate();
}
public static void main(String[] args) {
new CardLayoutDemo();
}
}
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/131592.html原文链接:https://javaforall.cn
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有