Java卡片布局(CardLayout)

编程知识 行业动态 更新时间:2024-06-13 00:21:18

_(:з」∠)_在书本例子的基础上做了点改动

package t4;

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

//让包含事件源的容器对象来担任监听者
public class App14_4 extends JFrame implements ActionListener {
	
	static App14_4 frm = new App14_4();
	static JPanel cardPan = new JPanel();	//使用卡片布局的容器
	static JPanel btPan = new JPanel();		//使用网格布局容器
	static CardLayout crd = new CardLayout(5,10);	//定义卡片布局对象crd
	static JButton bt1 = new JButton("第一页");
	static JButton bt2 = new JButton("上一页");
	static JButton bt3 = new JButton("下一页");
	static JButton bt4 = new JButton("最后页");
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		bt1.addActionListener(frm);		//向按钮们注册监听者frm
		bt2.addActionListener(frm);
		bt3.addActionListener(frm);
		bt4.addActionListener(frm);
		
		//设置窗口
		frm.setLayout(null);	
		frm.setTitle("卡片式布局策略CardLayout");
		frm.setSize(350,300);
		frm.setResizable(false);
		
		//设置使用卡片布局的容器
		cardPan.setLayout(crd);		
		cardPan.setBounds(10, 10, 320, 200);
		for(int i=1;i<=4;i++) {
			cardPan.add(new JTextArea("第"+i+"页"));
		}
		
		//设置使用网格布局的容器
		btPan.setLayout(new GridLayout(1,4));
		btPan.setBounds(10, 220, 320, 25);
		btPan.add(bt1);
		btPan.add(bt2);
		btPan.add(bt3);
		btPan.add(bt4);
		
		frm.add(cardPan);
		frm.add(btPan);
		frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frm.setVisible(true);
	}
	
	public void actionPerformed(ActionEvent e) {
		JButton bt = (JButton)e.getSource();
		if(bt == bt1)
			crd.first(cardPan);
		else if(bt == bt2)
			crd.previous(cardPan);
		else if(bt == bt3)
			crd.next(cardPan);
		else
			crd.last(cardPan);
	}
}

更多推荐

Java卡片布局(CardLayout)

本文发布于:2023-03-31 14:14:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/5e59f679ccd8c457ff55ff338d7cac08.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:卡片   布局   Java   CardLayout

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!