GUI布局管理器 事件处理

CardLayout:卡片布局

布局效果:将多个组件在同一容器区域内交替显示,相当于多张卡片摞在一起,只有最上面的卡片是可见的。

构造方法
public CardLayout()
public CardLayout(inthgap, intvgap)

其他方法
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);

JDKjava.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();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值