CardLayout:卡片布局
布局效果:将多个组件在同一容器区域内交替显示,相当于多张卡片摞在一起,只有最上面的卡片是可见的。
构造方法
public CardLayout()
public CardLayout(int hgap, int vgap)
其他方法
public void first(Container parent)—显示第一张卡片
public void last(Container parent)—显示最后一张卡片
public void previous(Container parent)—显示前一张卡片
public void next(Container parent)—显示后一张卡片
public void show(Container parent,String name)
示例4:卡片布局的使用。
Frame f=new Frame("CardLayoutExample");
CardLayout c1=new CardLayout();
f.setLayout(c1);
Label lbl[]=new Label[4];
for(int i=0;i<4;i++){
lbl[i]=newLabel("第"+i+"页");
f.add(lbl[i],"card"+i);
}
while(true){
try{
Thread.sleep(1000);
}catch(InterruptedExceptione){
e.printStackTrace();
}
c1.next(f);
}
示例:委托事件模型的分析。
事件源:按钮
触发事件:ActionEvent
事件监听器:
import java.awt.event.*;
public class MyEventListenerimplements ActionListener{
publicvoid actionPerformed(ActionEvent e){
System.out.println("Abutton has been pressed!");
}
}
Frame frame=newFrame("TestActionEvent");
Button btn=new Button("ClickMe!");
MyEventListener mel=new MyEventListener();
btn.addActionListener(mel);
frame.setLayout(new FlowLayout());
frame.add(btn);
frame.setSize(200,100);
frame.setVisible(true);
JDK的java.awt.event包中定义了一系列的事件监听器接口,在这些接口中分别定义了各种类型的Java GUI 事件的处理方法,只有实现了这些接口的类对象才有资格作监听器,去处理相应类型的事件。
事件监听器类型和对应的事件处理方法都是事先约定好的
所有事件处理方法的返回值类型均为void
示例2:窗口的事件处理。
classWindowHandler implements WindowListener{
voidwindowClosing(WindowEvent){
System.exit(0);
}
voidwindowOpened(WindowEvent e){}
voidwindowIconified(WindowEvent e){}
voidwindowDeiconified(WindowEvent e){}
voidwindowClosed(WindowEvent e){}
voidwindowActivated(WindowEvent e){}
voidwindowDeactivated(WindowEvent e){}
}
public classMyFrame extends Frame{
publicMyFrame(){
super("框架窗口的Window事件");
WindowHandlerhandler=new WindowHandler();
addWindowListener(handler);
setSize(150,100);
setVisible(true);
}
publicstatic void main(String[] args){
MyFrameframe=new MyFrame();
}
}