计算机二级:事件监听器的四种实现方式
有以下方法:
自身类作为事件监听器
外部类作为事件监听器
匿名内部类作为事件监听器
内部类作为事件监听器
自身类作为事件监听器:
导入javax . swing . *;
导入Java . awt . *;
导入Java . awt . event . *;
/**
*Java事件处理机制:自身类充当事件监听器
* @作者www.examda.com]
* @ version 2008-12-3
*/
Class this Class
public this Class event(){
super(" Java事件监听机制");
set layout(new FlowLayout());
setDefaultCloseOperation(JFrame。EXIT _ ON _ CLOSE);
BTN = new JButton(" click ");
BTN . addactionlistener(this);
getContentPane()。添加(BTN);
setBounds(200,200,300,160);
set visible(true);
}
/* * * * * */
public void action performed(action event e){
Container c = getcontent pane();
c . set background(color . red);
}
/* * * * * */
public static void main(String args[]){
new thiclassevent();
}
}
外部类充当事件侦听器:
import Java . awt . *;
导入Java . awt . event . *;
导入javax . swing . *;
/**
*Java事件处理机制:外部类充当事件监听器
* @ authorexamda.com]
* @ version 2008-12-3
*/
classeouterclasseventext
public outer class(){
Super(" Java事件监听机制");
set layout(new FlowLayout());
setDefaultCloseOperation(JFrame。EXIT _ ON _ CLOSE);
BTN = new JButton(" click ");
BTN . addactionlistener(new outer class(this));
getContentPane()。添加(BTN);
setBounds(200,200,300,160);
set visible(true);
}
public static void main(String args[]){
new outer class event();
}
}
/*外部类/
Classouter类实现操作侦听器{
outer Class seven oce;
public outer class(OuterClassEvent oce){
this . oce = oce;
}
public void action performed(action event e){
Container c = oce . getcontentpane();
c . set background(color . red);
}
}
/* * * */
匿名内部类充当事件侦听器:
import Java . awt . *;
导入Java . awt . event . *;
导入javax . swing . *;
/**
*Java事件处理机制:匿名内部类充当事件监听器
* @ version2008-12-3
类匿名事件扩展JFrame {
JButton BTN
public Anonymous Event(){
super(" Java事件监听机制");
set layout(new FlowLayout());
setDefaultCloseOperation(JFrame。EXIT _ ON _ CLOSE);
BTN = new JButton(" click ");
/*匿名内部类*/
BTN . addactionlistener(
NewActionListener(){
Public Void action performed(action event){
Container C = GetContentPane();
c . set background(color . red);
}
}
);
/* * * * * */
get content pane()。添加(BTN);
setBounds(200,200,300,160);
set visible(true);
}
public static void main(String args[]){
new AnonymousEvent();
}
}
内部类充当事件侦听器:
import Java . awt . *;
导入Java . awt . event . *;
导入javax . swing . *;
/**
*Java事件处理机制:内部类充当事件监听器
* @作者www.examda.com]
* @ version 2008-12-3
*/
Class inner
public inner Class Event(){
Super(" Java事件监听机制");
set layout(new FlowLayout());
setDefaultCloseOperation(JFrame。EXIT _ ON _ CLOSE);
BTN = new JButton(" click ");
BTN . addactionlistener(new InnerClass());
getContentPane()。添加(BTN);
setBounds(200,200,300,160);
set visible(true);
}
/* inner class */
class inner class实现操作侦听器{
public void action performed(action evente){
container c = getcontent pane();
c . set background(color . red);
}
}
public static void main(String args[]){
new innerclass event();
}
}
0条评论