事件处理初级篇

     事件处理

基本元素:

事件源: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持有对方引用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值