第一次对监听器的使用
监听器:是一个监听器接口的实例,并且必须注册到源对象上
监听器实现监听器接口
监听器实际上是一个类 这个类实现了监听器接口
创建监听器注册到源对象上面
注册方法:调用source.addActionListener()来注册
事件是事件源向事件监听器传输事件源状态信息的载体
![](https://img-blog.csdn.net/20160815150335606)
/**
* 一个类实现监听的步骤:
* 1.实现相应的接口
* 2.把接口的处理方法根据需要重新编写
* 3.把时间源注册监听
* 4.事件传到事件对象
*/
第一步(70行):创建EnlargeListener 类 实现 ActionListener接口
第二步(28行):new一个监听器 ,再注册到button1上
第三步(54行):创建enlarge方法 以被调用
第四步(74行):覆盖接口中的actionPerformed方法 一旦监听到该操作 执行下一句 调用enlarge方法
第五步(71行):为了让actionPerformed能访问enlarge方法 ,将该类定义成inner class
- package chapter16;
-
- import java.awt.BorderLayout;
- import java.awt.Graphics;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
-
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JPanel;
-
- @SuppressWarnings("serial")
- public class ControlCircle1 extends JFrame {
- private circle1 circle = new circle1(20);
- private JButton button1 = new JButton("Enlarge");
- private JButton button2 = new JButton("Shrink");
-
- public ControlCircle1() {
-
- JPanel p1 = new JPanel();
- p1.add(button1);
- p1.add(button2);
-
- add(circle, BorderLayout.CENTER);
- add(p1, BorderLayout.SOUTH);
-
-
- button1.addActionListener(new EnlargeListener());
- button2.addActionListener(new ShrinkListener());
- }
-
- public static void main(String[] args) {
- ControlCircle1 a = new ControlCircle1();
-
- a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- a.setLocationRelativeTo(null);
- a.setVisible(true);
- a.setTitle("displayshow");
- a.setSize(300, 300);
- }
-
-
- class circle1 extends JPanel {
- private int radius = 5;
-
- public circle1() {
-
- }
-
- public circle1(int radius) {
- this.radius = radius;
- }
-
- public void enlarge() {
- radius +=20;
- repaint();
- }
- public void shrink(){
- radius-=5;
- repaint();
- }
-
- protected void paintComponent(Graphics g) {
- super.paintComponent(g);
- g.drawOval(getWidth() / 2 - radius, getHeight() / 2 - radius,
- 2 * radius, 2 * radius);
- }
- }
-
- class EnlargeListener implements ActionListener {
-
-
- @Override
- public void actionPerformed(ActionEvent e) {
- circle.enlarge();
- }
- }
- class ShrinkListener implements ActionListener{
-
- @Override
- public void actionPerformed(ActionEvent e) {
- circle.shrink();
- }
-
-
- }
- }
enlarge 和 shrink键是控制圆圈的放大和缩小
![](https://img-blog.csdn.net/20160815145533914)
![](https://img-blog.csdn.net/20160815145538992)