事件处理
基本元素:
事件源:event source
产生事件的对象。
监听器:event listerner
监听对象事件并处理的对象。
关系如下图:
事件源 <>------------监听器
即一对多的关系。
举个例子说明一下工作原理:
按钮监听器注册后,监听事件,当按钮被点击,触发event,监听器根据event的信息进行处理。
监听器(implements interface Listener)可以是下面三种形式:
1单独的类
2内部类
3匿名类
程序例子:
最长用的是内部类,我们就以他为例,写个小例子:
点击不同的按钮时,背景色会变化,代码如下:
package event;
/**
*SetBackgroundWin.java
* Created on 8:12:50 AM Feb 27, 2009
*@author Quasar063501
*@version 0.1
*
*/
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SetBackgroundWin extends JFrame{
public void launchFrame() {
this.setLayout(new GridLayout(2,1));
this.add(new ContentsPanel(this));
this.pack();
this.setVisible(true);
}
public static void main(String[] args) {
new SetBackgroundWin().launchFrame();
}
private class ContentsPanel extends JPanel {
private SetBackgroundWin sbw = null;
private JButton bR = null;
private JButton bG = null;
private JButton bB = null;
public ContentsPanel(SetBackgroundWin sbw) {
this.sbw = sbw;
bR = new JButton("Red");
bG = new JButton("Green");
bB = new JButton("Blue");
bR.addActionListener(new RButtonListener());
bG.addActionListener(new GButtonListener());
bB.addActionListener(new BButtonListener());
this.setLayout(new GridLayout(2,3));
this.add(bR);
this.add(bG);
this.add(bB);
this.setVisible(true);
}
private class RButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
setBackground(Color.RED);
}
}
private class GButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
setBackground(Color.GREEN);
}
}
private class BButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
setBackground(Color.BLUE);
}
}
}
}
注:一个类的定义中若想访问另一个类的几种方法:
1内部类
2持有对方引用