您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
javase第三季学习笔记-事件处理
发布时间:2017-08-10 15:59:06编辑:雪饮阅读()
事件的基本概念
• 事件处理:
• 事件(Event):用户对组件的一个操作,称之为一个事件
• 事件源(Event source) :产生事件的对象
• 事件处理方法(Event handler) : 能够接收、解析和处理事件类对象、实现和用户交互的方法 ,事件监听器。
事件类型
事件类型 |
相应监听器接口 |
Action |
ActionListener |
Item |
ItemListener |
Mouse |
MouseListener |
Mouse Motion |
MouseMotionListener |
Key |
KeyListener |
Focus |
FocusListener |
Window |
WindowListener |
Text |
TextListener |
使用事件处理实现窗体右上角的关闭按钮功能:
默认的右上角关闭按钮是点击无效的。
我们需要监听窗体捕获事件进行处理。
首先自定义一个类并实现一个接口WindowListener:
该接口有好多方法,我们就实现它的窗口关闭方法windowClosing
class MyWindowListener implements WindowListener{
@Override
public void windowOpened(WindowEvent e) {
}
@Override
public void windowClosing(WindowEvent e) {
//退出程序
System.exit(0);
}
@Override
public void windowClosed(WindowEvent e) {
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowActivated(WindowEvent e) {
}
@Override
public void windowDeactivated(WindowEvent e) {
}
}
然后使用该自定义类给窗体添加上监听事件:
this.addWindowListener(new MyWindowListener());
给登录按钮添加上动作执行监听:
然后就会生成代码如下:
private Button getButton_login() {
if (button_login == null) {
button_login = new Button();
button_login.setLabel("登录");
button_login.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
System.out.println("actionPerformed()"); // TODO Auto-generated Event stub actionPerformed()
}
});
}
return button_login;
}
自定义修改该方法为:
private Button getButton_login() {
if (button_login == null) {
button_login = new Button();
button_login.setLabel("登录");
button_login.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
//获取文本框的内容
String username=textField_username.getText();
String password=textField_password.getText();
if("admin".equals(username) && "123".equals(password)){
System.out.println("登录成功!");
}
else{
System.out.println("登录失败,请检查用户名和密码!");
}
}
});
}
return button_login;
}
事件适配器
• 为简化编程,针对大多数事件监听器接口定义了相应的实现类----事件适配器类,在适配器类中,实现了相应监听器接口中所有的方法,但不做任何事情。
• 在定义监听器类时就可以继承事件适配器类,并只重写所需要的方法
• 常用的适配器
– FocusAdapter (焦点适配器)
– KeyAdapter(键盘适配器)
– MouseAdapter (鼠标适配器)
– MouseMotionAdapter (鼠标运动适配器)
– WindowAdapter (窗口适配器)
使用适配器实现窗体关闭按钮事件:
适配器方式更简洁,不需要独立建立一个自定义的类
下面代码放置在构造方法中initialize()的后面
//适配器方式监听窗体关闭按钮事件
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.out.println("exit");
System.exit(0);
}
});
关键字词:javase,事件处理
上一篇:javase第三季学习笔记-枚举