事件处理可以简单地这么理解,当有一个事件产生,程序要根据这个事件做出响应。比如,我们做了一个可以通过按钮改变背景颜色的窗口,当我们点击按钮时便产生了一个事件,程序会根据这个事件来做出响应,也就是去改变背景的颜色。

运行结果

  那么程序是怎样做出响应的呢?这就需要事件监听器ActionListener,这是一个接口,里面包含了actionPerformed方法(也就是根据事件去执行的操作),所以我们要实现这个接口(实现接口里的actionPerformed方法)做出一个监听器对象出来,并且用按钮来注册这个监听器对象,这样当按钮被点击的时候,就会调用这个监听器来执行响应了。

事件处理机制

  代码(第42行开始为实现接口):

 package buttonPanel;

 import java.awt.*;
import java.awt.event.*; //事件监听器接口ActionListener的位置。
import javax.swing.*; public class ButtonFrame extends JFrame {
private ButtonPanel buttonPanel;
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200; public ButtonFrame() {
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
setLocationByPlatform(true); //构造按钮
JButton redButton = new JButton("RED");
JButton yellowButton = new JButton("YELLOW");
JButton blueButton = new JButton("BLUE"); buttonPanel = new ButtonPanel(); //添加按钮到面板
buttonPanel.add(redButton);
buttonPanel.add(yellowButton);
buttonPanel.add(blueButton); add(buttonPanel); //构造对应颜色的动作监听器
ColorAction redAction = new ColorAction(Color.red);
ColorAction yellowAction = new ColorAction(Color.yellow);
ColorAction blueAction = new ColorAction(Color.blue); //每个按钮注册对应的监听器
redButton.addActionListener(redAction);
yellowButton.addActionListener(yellowAction);
blueButton.addActionListener(blueAction);
} //为了方便调用buttonPanel,将ColorAction作为ButtonFrame的内部类。
private class ColorAction implements ActionListener {
private Color backgroundColor;
public ColorAction(Color c) {
backgroundColor = c;
}
public void actionPerformed(ActionEvent event) {
buttonPanel.setBackground(backgroundColor);
}
} public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame frame = new ButtonFrame();
frame.setTitle("ColorButton");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
} class ButtonPanel extends JPanel {
private static final int DEFAUT_WIDTH = 300;
private static final int DEFAUT_HEIGHT = 200; @Override
protected void paintComponent(Graphics g) {
g.create();
super.paintComponent(g);
} @Override
public Dimension getPreferredSize() {
return new Dimension(DEFAUT_WIDTH,DEFAUT_HEIGHT);
}
}

ButtonFrame

  -------------------------------------------------------------------------------------------------------------------------

  在上述代码中,为了方便监听器调用buttonPanel,将ColorAction作为ButtonFrame的内部类。如果将ColorAction类独立出去,需要将buttonPanel传递到ColorAction,实现如下:

 package buttonPanel2;

 import java.awt.*;
import java.awt.event.*;
import javax.swing.*; public class ButtonFrame2 extends JFrame {
private ButtonPanel buttonPanel;
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200; public ButtonFrame2() {
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
setLocationByPlatform(true); JButton redButton = new JButton("RED");
JButton yellowButton = new JButton("YELLOW");
JButton blueButton = new JButton("BLUE"); buttonPanel = new ButtonPanel(); buttonPanel.add(redButton);
buttonPanel.add(yellowButton);
buttonPanel.add(blueButton); add(buttonPanel); //将此对象通过this传到ColorAction的构造器。
ColorAction redAction = new ColorAction(this,Color.red);
ColorAction yellowAction = new ColorAction(this,Color.yellow);
ColorAction blueAction = new ColorAction(this,Color.blue); redButton.addActionListener(redAction);
yellowButton.addActionListener(yellowAction);
blueButton.addActionListener(blueAction);
} public void setButtonPanelsBackground(Color backgroundColor) {
buttonPanel.setBackground(backgroundColor);
} public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame frame = new ButtonFrame2();
frame.setTitle("ColorButton");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
} class ColorAction implements ActionListener {
private ButtonFrame2 buttonFrame;
private Color backgroundColor; //通过构造器的方法把ButtonFrame2对象传过来,这个对象包含了成员变量buttonPanel,以便对其更换背景色。
public ColorAction(ButtonFrame2 buttonFrame,Color c) {
this.buttonFrame = buttonFrame; //this.buttonFrame只是对象管理者,管理的还是ButtonFrame的对象frame。
backgroundColor = c;
}
public void actionPerformed(ActionEvent event) {
buttonFrame.setButtonPanelsBackground(backgroundColor);
//这是我们在ButtonFrame2中添加的新方法。
}
} class ButtonPanel extends JPanel {
private static final int DEFAUT_WIDTH = 300;
private static final int DEFAUT_HEIGHT = 200; public ButtonPanel() {
setBackground(Color.pink);
} @Override
protected void paintComponent(Graphics g) {
g.create();
super.paintComponent(g);
} @Override
public Dimension getPreferredSize() {
return new Dimension(DEFAUT_WIDTH,DEFAUT_HEIGHT);
}
}

ButtonFrame2

  --------------------------------------------------------------------------------------------------------

  代码存在一个缺陷,就是在构造按钮、添加按钮到面板、构造相应颜色的监听器和注册监听器的时候有代码复制的情况,为了避免代码复制,我们可以创建一个makeButton方法,把这些重复的操作包含在内,实现如下:

 package buttonPanel3;

 import java.awt.*;
import java.awt.event.*;
import javax.swing.*; public class ButtonFrame3 extends JFrame {
private ButtonPanel buttonPanel;
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200; public ButtonFrame3() {
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
setLocationByPlatform(true); buttonPanel = new ButtonPanel();
add(buttonPanel); makeButton("RED",Color.red);
makeButton("YELLOW",Color.yellow);
makeButton("BLUE",Color.blue);
} //为了避免代码重复,我们将重复的操作放在这个函数里。
public void makeButton(String name,final Color bg) {
JButton button = new JButton(name);
buttonPanel.add(button);
button.addActionListener(new ActionListener() { //可以new一个接口出来,但是后面必须接花括号实现内部方法。
public void actionPerformed(ActionEvent event) {
buttonPanel.setBackground(bg);
}
});
} public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame frame = new ButtonFrame3();
frame.setTitle("ColorButton");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
} class ButtonPanel extends JPanel {
private static final int DEFAUT_WIDTH = 300;
private static final int DEFAUT_HEIGHT = 200; @Override
protected void paintComponent(Graphics g) {
g.create();
super.paintComponent(g);
} @Override
public Dimension getPreferredSize() {
return new Dimension(DEFAUT_WIDTH,DEFAUT_HEIGHT);
}
}

  在代码中,监听器只被调用了一次,也就是在addActionListener()时。所以我们没有必要为监听器单独做一个类出来,而是只需在用到监听器时直接new一个ActionListener接口出来,并在花括号里实现接口方法即可。

  --------------------------------------------------------------------------------------------------------

  但是有些程序员喜欢将因事件而改变的容器作为实现接口的监听器,代码如下,这样会显得混乱,我们不建议这么做:

 package buttonPanel4;

 import java.awt.*;
import java.awt.event.*;
import javax.swing.*; //将buttonPanel所在的ButtonFrame4实现接口。
public class ButtonFrame4 extends JFrame implements ActionListener {
private ButtonPanel buttonPanel;
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200; public ButtonFrame4() {
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
setLocationByPlatform(true); buttonPanel = new ButtonPanel();
add(buttonPanel); makeButton("RED");
makeButton("YELLOW");
makeButton("BLUE");
} public void makeButton(String name) {
JButton button = new JButton(name);
buttonPanel.add(button);
button.addActionListener(this);
//直接注册this这个接口。
} //覆盖接口方法,String getActionCommand()为java.awt.event.ActionEvent的方法,返回动作事件相关的命令字符串,在这里等于按钮标签。
//需要用到if else选择语句。
@Override
public void actionPerformed(ActionEvent event) {
String c = event.getActionCommand();
if(c == "RED") {
buttonPanel.setBackground(Color.red);
}else if(c == "YELLOW") {
buttonPanel.setBackground(Color.yellow);
}else {
buttonPanel.setBackground(Color.blue);
}
} public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame frame = new ButtonFrame4();
frame.setTitle("ColorButton");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
} class ButtonPanel extends JPanel {
private static final int DEFAUT_WIDTH = 300;
private static final int DEFAUT_HEIGHT = 200; @Override
protected void paintComponent(Graphics g) {
g.create();
super.paintComponent(g);
} @Override
public Dimension getPreferredSize() {
return new Dimension(DEFAUT_WIDTH,DEFAUT_HEIGHT);
}
}

ButtonFrame4

Java基础学习 -- GUI之 事件处理基础的更多相关文章

  1. Jquery学习笔记:事件处理基础介绍

    一.引子 给html的元素添加一个响应事件,最简单的办法是直接在元素标签内填写事件属性,先看一个最简单的例子 <!DOCTYPE html> <html lang="zh- ...

  2. Java基础学习之数据类型、基础语法与数组(3)

    目录 1.数据类型 1.1.基本数据类型 1.2.引用数据类型 1.3.自动装箱与拆箱 2.基础语法 2.1.标识符 2.2.修饰符 2.2.1.访问控制修饰符 2.2.2.非访问控制修饰符 2.3. ...

  3. 零基础学习java------day1------计算机基础以及java的一些简单了解

    一. java的简单了解 Java是一门面向对象编程语言,不仅吸收了C++的各种优点,还摒弃了C++里难以理解的多继承.指针等概念,因此Java语言具有功能强大和简单易用两个特征.Java语言作为静态 ...

  4. Java反射学习总结一(基础篇)

    Class类是Reflection API中核心的类,他位于Java.lang.Class 列出一些常用的方法. - getName() : 获得类的完整名字 - getFields() : 获得类的 ...

  5. 最全java多线程学习总结1--线程基础

      <java 核心技术>这本书真的不错,知识点很全面,翻译质量也还不错,本系列博文是对该书中并发章节的一个总结. 什么是线程   官方解释:线程是操作系统能够进行运算调度的最小单位,包含 ...

  6. Java多线程学习笔记之一线程基础

    1.进程与线程 1.1 进程:是正在运行中的程序的实例,一个运行中idea就是一个进程.进程有它自己的地址空间,一般情况下,包括文本区域(text region).数据区域(data region)和 ...

  7. Java基础学习笔记(二) - 面向对象基础

    面向对象 一.面向对象概述 面向对象思想就是在计算机程序设计过程中,参照现实事物,将事物的属性特征.行为特征抽象出来,描述成计算机时间的设计思想.面向对象思想区别于面向过程思想,强调的是通过调用对象的 ...

  8. core java 8~9(GUI & AWT事件处理机制)

    MODULE 8 GUIs--------------------------------GUI中的包: java.awt.*; javax.swing.*; java.awt.event.*; 要求 ...

  9. python 的基础 学习 第五天 基础数据类型的操作方法

    1,列表的基本操作方法 1,列表是python中的基础数据类型之一,其他语言中也有类似于列表的数据类型,比如js中叫数组,他是以[ ]括起来,每个元素以逗号隔开,而且他里面可以存放各种数据类型比如: ...

随机推荐

  1. Utility2:Appropriate Evaluation Policy

    UCP收集所有Managed Instance的数据的机制,是通过启用各个Managed Instances上的Collection Set:Utility information(位于Managem ...

  2. Sql Server系列:自定义函数

    用户自定义函数可以像系统函数一样在查询或存储过程中调用,可以接受参数.执行操作并将操作结果以值的形式返回.返回值可以是单个标量或结果集. 1. 标量函数 标量函数返回一个确定类型的标量值,对于多语句的 ...

  3. 【WP 8.1开发】如何动态生成Gif动画

    相信如何为gif文件编码,很多朋友都会,而难点在于怎么让GIF文件中的帧动起来,也就是创建gif动画. Gif文件编码方法 先简单介绍一下编码的方法. 1.调用BitmapEncoder.Create ...

  4. iTween 动画类型

    iTween 动画类型 http://robertpenner.com/easing/easing_demo.html 使用范例 http://www.xuanyusong.com/archives/ ...

  5. ScrollView 嵌套ListView、RecyclerView(持续更新)

    ListView: 只要重写ListView或GridView的onMeasure()方法即可: @Override protected void onMeasure(int widthMeasure ...

  6. Android性能优化之UncaughtExceptionHandler定制自己的错误日志系统

    前言: 每当我们app测试的时候,测试人员总是对我们说这里崩溃了,那里挂掉了!我们只能默默接受,然后尝试着重现bug,更可悲的是有时候bug很难复现,为了解决这种现状所以我们要尝试这建立一个自己的bu ...

  7. DDD 领域驱动设计-在动手之前,先把你的脑袋清理干净

    惨不忍睹的翻译 英文原文:http://www.codeproject.com/Articles/339725/Domain-Driven-Design-Clear-Your-Concepts-Bef ...

  8. C语言 编程练习22题

    一.题目 1.编一个程序,输入x的值,按下列公式计算并输出y值: 2.已知数A与B,由键盘输入AB的值,交换它们的值,并输出. 3.给一个不多于5位的正整数,要求:一.求它是几位数,二.逆序打印出各位 ...

  9. (十一)WebGIS中要素(Feature)的设计

    文章版权由作者李晓晖和博客园共有,若转载请于明显处标明出处:http://www.cnblogs.com/naaoveGIS/. 1.前言 在GIS中元素一般分为点元素,线元素,面元素以及symbol ...

  10. Linux服务器(Ubuntu14.04)添加远程连接VNC Server

    1.打开终端输入:sudo apt-get install xrdp,   2. sudo apt-get install vnc4server ,  3. sudo apt-get install ...