Java基础入门 CardLayout

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40788630/article/details/82290731

在操作程序中,我们时常会选项卡按钮实现程序界面的切换,这些界面就相当于一张一张卡片,而管理这些卡片的布局管理器就是卡片布局管理器(CardLayout)。卡片布局管理器将界面看做一系列卡片,在任何时候只要其中一张卡片是可见的,那么这张卡片将占据容器的整个区域。在CardLayout布局管理器中经常会用到下面几个方法:

CardLayout常用方法
方法说明 功能描述
void first(Container parent) 显示parent容器的第一张卡片
void last(Container parent) 显示parent容器的最后一张卡片
void previous(Container parent) 显示parent容器的上一张卡片
void next(Container parent) 显示parent容器的下一张卡片
void show(Container parent,String name) 显示parent容器中名称为name的卡片,如果不存在,则不会发生任何操作

上面列举了CardLayout的常用方法,下面通过一个案例来演示:

import java.awt.*;
import java.awt.event.*;

class Mycardlayout extends Frame implements ActionListener{
	Panel cardPanel =new Panel();//创建卡片面板
	Panel controlpaPanel =new Panel();//创建控制面板
	Button nextbutton,preButton;//创建控制按钮
	CardLayout cardlayout=new CardLayout();//定义布局对象
	public Mycardlayout(){
		this.setSize(300,200);
		this.setVisible(true);
		this.addWindowListener(new WindowAdapter(){//为窗口添加监听器
			public void windowClosing(WindowEvent e){
				Mycardlayout.this.dispose();
			}
		});
		
		cardPanel.setLayout(cardlayout);//设置cardPanel布局类型
		cardPanel.add(new Label("第一张界面", Label.CENTER));//在cardPanel面板中连续插入三个界面
		cardPanel.add(new Label("第二张界面", Label.CENTER));//Label对象是用于将文本放置在容器中的组件。 标签显示一行只读文本
		cardPanel.add(new Label("第三张界面", Label.CENTER));
		
		nextbutton=new Button("下一张卡片");//创建两个按钮
		preButton=new Button("上一张卡片");
		
		nextbutton.addActionListener(this);//为两个按钮注册监听器
		preButton.addActionListener(this);
		
		controlpaPanel.add(preButton);//将两个按钮添加到controlpaPanel(控制面板)中
		controlpaPanel.add(nextbutton);
		
		this.add(cardPanel, BorderLayout.CENTER);//将卡片面板添加到窗体中部
		this.add(controlpaPanel, BorderLayout.SOUTH);//将控制面板添加到窗体南部
		this.setTitle("CardLayout");
	}
	//下面的代码实现了按钮的监听触发,并对触发进行处理
	public void actionPerformed(ActionEvent e){
		if(e.getSource()==nextbutton){//如果用户点击nextbutton则切换cardPanel之后的组件
		                              //getSource()的作用是获得事件最初发生的对象。
			cardlayout.next(cardPanel);
		}
		if(e.getSource()==preButton){//如果用户点击preButton咋切换cardPanel之前的组件
			cardlayout.previous(cardPanel);
		}
	}
}
public class Main{
	public static void main(String[] args)throws Exception{
        new Mycardlayout();
	}
}

猜你喜欢

转载自blog.csdn.net/qq_40788630/article/details/82290731