java 软件设计基础

63
Java 软软软软软软 图图图图图图图图图图图图 图图图图图图图图图图图图

Upload: jacob-miranda

Post on 30-Dec-2015

85 views

Category:

Documents


8 download

DESCRIPTION

Java 软件设计基础. 图形用户界面程序设计入门. 1. 组件概述. GUI: Graphics User Interface 设计和实现 GUI 的主要难点 创建组成界面的各成分和元素,指定它们的属性和位置关系,根据具体需要布局排列,从而构成完整的 GUI 的 外观表象 ; 在 GUI 程序中,代码所执行的路线及顺序都是很不确定的。在 GUI 程序中,用户可以点击任意按键并和屏幕上的其他任何部分进行交互及信息传递 —— 即 事件驱动 。 Java 提供了大量支持 GUI 设计的类。 AWT(Abstract Window Tookit) 包 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Java 软件设计基础

Java软件设计基础

图形用户界面程序设计入门图形用户界面程序设计入门

Page 2: Java 软件设计基础

School of Computer Science and Technology

1. 组件概述

• GUI: Graphics User InterfaceGUI: Graphics User Interface–设计和实现GUI的主要难点

•创建组成界面的各成分和元素,指定它们的属性和位置关系,根据具体需要布局排列,从而构成完整的GUI的外观表象;

•在 GUI程序中,代码所执行的路线及顺序都是很不确定的。在GUI程序中,用户可以点击任意按键并和屏幕上的其他任何部分进行交互及信息传递——即事件驱动。

• JavaJava提供了大量支持提供了大量支持 GUIGUI设计的类。设计的类。–AWT(Abstract Window Tookit)包

•Button、 Label、 TextField、 CheckBox…

–Swing包•JButton、 JLabel、 JTextField、 JCheckBox…

Page 3: Java 软件设计基础

School of Computer Science and Technology

• SwingSwing和和 AWTAWT–对 Java运行的每一个平台, AWT的组件自动的通过它们各自的代理映射成特定平台的组件,这些代理称为同位体 (peer)。

•AWT组件的设计原理是把与显示组件有关的许多工作和处理组件事件的工作交给相应的本地组件,因此非常依赖底层平台;

•AWT适用于开发简单的GUI,但不适于开发复杂的GUI项目。–随着 Java 2的发行, AWT的用户界面组件被更稳定、通用和灵活的 Swing组件库取代。

•大多数 Swing组件由 Java代码绘制在画布上,更少的依赖目标机器上的底层平台。

不依赖本地 GUI 的 Swing 组件称为轻组件—— Lightweight component ; AWT 组件称为重组件—— Heavyweight component 。

Page 4: Java 软件设计基础

School of Computer Science and Technology

• SwingSwing外观与外观与WindowsWindows外观外观

Page 5: Java 软件设计基础

School of Computer Science and Technology

• Java GUI APIJava GUI API层次结构层次结构

java.awt

BorderLayout

CardLayout

CrodLayout

FlowLayout

Component

GridBagLayout

Panel

Canvas

Checkbox

Choice

Button

Label

Applet

List

Scrollbar

TextComponent

Container

MenuComponent Menubar

MenuItemAWTEvent

Window Dialog

FrameCheckBoxMenuItem

Menu PopupMenu

Page 6: Java 软件设计基础

School of Computer Science and Technology

J Component

AbstractButton

J TextComponent

J MenuItem

J Button

J ToggleButton

J CheckBoxMenuItem

J Menu

J RadioButtonMenuItem

J CheckBox

J RadioButtonJ EditorPane

J TextField

J TextArea

J Label J List J ComboBox J Panel J OptionPane J ScrollBar J Slider

J TabbedPane J SplitPane J LayeredPane J Separator J ScrollPane J RootPane

J ToolBar J MenuBar J PopupMenu J FileChooser J ColorChooser J ToolTip

J Tree J Table J TableHeader J InternalFrame J ProgressBar J Spinner

Page 7: Java 软件设计基础

School of Computer Science and Technology

• GUIGUI类类–容器类 (Container)

•用来包含其他组件;Window、 Panel、 Applet、 Frame和 Dialog都是 AWT组件的容器类; Conponent、 Container、JFrame 、 JDialog 、 JApplet 和 JPanel 都是 Swing 的容器类。其中:

–Container用来组织组件;–JFrame是不能包含在另一个窗口内的窗口;–JDialog是一个弹出式窗口或消息框;–JApplet是 Applet的一个子类;–JPanel是一个存放用户界面组件的不可见的容器,可以嵌套。

–组件类 (Component)•组件是一个可以以图形化方式显示于屏幕上与用户进行交互的对象。

–按钮、菜单、标签、文本域、复选框……

Page 8: Java 软件设计基础

School of Computer Science and Technology

–辅助类•辅助类都不是 Component的子类,它们用来描述 GUI组件的

属性,例如颜色、字体、大小等。–Graphics类是一个抽象类,提供一个图形环境,用于绘制字符串、直线和简单几何图形;–Color类用来处理GUI组件的颜色;–Font类指定GUI组件上文本和图形的字体;–FontMetrics是用于获取字体属性的抽象类;–Dimension将组件的宽度和高度(精度为整数)封装在单个对象中;–LayoutManager是一个接口,指定组件在容器中的摆放方式。

•辅助类包含在 AWT包中。•Swing组件不能取代 AWT的全部类,只能替代 AWT的 GUI

组件类; AWT的辅助类保持不变。

Page 9: Java 软件设计基础

School of Computer Science and Technology

• GUIGUI设计的简要流程设计的简要流程–引入 java.awt包或 javax.swing包;–利用包中提供的组件类来定义某种组件;–定义一个放置组件的容器;–对容器进行布局管理,将此组件添加到该容器中;–为了让该组件响应某个事件,还要注册组件对应的事件监听器并实现相应的监听器接口。

Page 10: Java 软件设计基础

School of Computer Science and Technology

2. AWT图形化界面基础

• Frame/JFrame——Frame/JFrame—— 框架框架–Frame

•框架是 Windows 类的子类,它是窗口的一种,是顶 级窗口。 Frame组件在 Java的顶层窗口中可以独立使用。

•包含标题、边框等。•当 Frame被关闭后,将产生 WindowEvent事件。•Frame 无法直接监听键盘输入事件。•构造方法:

–建立一个没有标题的新 Frame对象:

–建立一个以 title为标题的 Frame对象:

Frame()Frame()

Frame(String title)Frame(String title)

Page 11: Java 软件设计基础

School of Computer Science and Technology

•主要方法:

setSize(int width, int height)setSize(int width, int height) 设置长宽设置长宽

setBackground(color c)setBackground(color c) 设置背景色设置背景色

setVisible(boolean b)setVisible(boolean b) 设置是否可见设置是否可见

String getTitle()String getTitle() 获取标题获取标题

setTitle(String title)setTitle(String title) 设置标题为设置标题为 titletitle

boolean isResizable()boolean isResizable() 测试是否可以改变大小测试是否可以改变大小

Image getIconImage()Image getIconImage() 获取最小化图标获取最小化图标

setIconImage(Image img)setIconImage(Image img) 设置最小化图标设置最小化图标

setBounds(int x, int y, int width, setBounds(int x, int y, int width, int height)int height)

设置大小和位置设置大小和位置

Page 12: Java 软件设计基础

School of Computer Science and Technology

创建带图标Frame框架import java.awt.*;import javax.swing.ImageIcon;public class Win_Frame{

static Frame yf = new Frame("This is a frame with icon");static ImageIcon icon = new ImageIcon("icon.gif");public static void main(String args[]){

yf.setBounds(0,0,200,100);yf.setResizable(false);yf.setBackground(Color.red);yf.setIconImage(icon.getImage());yf.setState(yf.NORMAL);yf.show();

}}

–示例:

Page 13: Java 软件设计基础

School of Computer Science and Technology

• Panel——Panel——面板面板–简介:

•是 Container类的子类,也是容器,可容纳其他组件。•面板不是顶级窗口,不能独立存在,必须将它添加到其他容器中。•创建一个 Panel对象后需将该对象放入Window和 Frame中

才可使 Panel中的内容可见。–构造方法:

•建立一个默认布局的新 Panel对象:

•建立一个布局为 layout的 Panel对象:

Panel()Panel()

Panel(LayoutManager layout)Panel(LayoutManager layout)

Page 14: Java 软件设计基础

School of Computer Science and Technology

–示例创建Panel

import java.awt.*;public class Win_Panel{

public static void main(String args[]){Frame f = new Frame("Panel");Panel p = new Panel();f.setSize(180,180);f.setBackground(Color.pink);f.setLayout(null);p.setSize(90,90);p.setBackground(Color.blue);f.add(p);p.setLocation(45,45);f.setVisible(true);

}}

Page 15: Java 软件设计基础

School of Computer Science and Technology

• Button——Button——按钮按钮–简介

•是 Java程序 GUI设计中最常用的一个组件,是可以提供用户快速启动某一动作的类。

•按钮本身不显示信息,它一般对应一个事先定义好的功能操作,并对应一段程序。

•当用户点击按钮时,系统自动执行与该按钮相联系的程序,从而完成预先指定的功能。

–构造方法•构造一个没有标题的按钮:

•构造一个标题为 str的按钮:Button()Button()

Button(String str)Button(String str)

Page 16: Java 软件设计基础

School of Computer Science and Technology

创建Buttonimport java.awt.*;public class Button1{

public static void main(String args[]){Frame f = new Frame("Button");Button b1 = new Button("Push me");Button b2 = new Button("You can not push me");f.setBounds(0,0,300,200);f.setLayout(null);b1.setBounds(10,40,100,40);b2.setBounds(10,100,200,40);b2.setEnabled(false);f.add(b1);f.add(b2);f.setVisible(true);

}}

–主要方法

–示例

String getLabel()String getLabel() 返回按钮的标题返回按钮的标题

setLabel(String s)setLabel(String s) 设置按钮的标题为设置按钮的标题为 ss

getActionCommand()getActionCommand() 返回所引用的返回所引用的 ButtonButton 对象产生的动作事件关联的命令名对象产生的动作事件关联的命令名称称

setActionCommand(StrisetActionCommand(String c)ng c)

设置所引用的设置所引用的 ButtonButton 对象产生的动作事件关联的命令名对象产生的动作事件关联的命令名称称

Page 17: Java 软件设计基础

School of Computer Science and Technology

• Label——Label—— 标签标签–简介

•是一种用来显示说明性的静态文本的组件,它起到信息说明的作用。•标签是用户只能查看而不能简单的修改其内容的文本显示区域,但

用户可以在应用程序中通过调用 Label提供的方法更换文本的内容。–构造方法

•创建一个没有名字的标签对象

•创建一个名字为 str的标签对象

•创建一个名字为 str的标签对象,对齐方式为 align

–其中 Label.LEFT、 Label.RIGHT、 Label.CENTER分别为居左、居右、居中。

Label()Label()

Label(String str)Label(String str)

Label(String str, int align)Label(String str, int align)

Page 18: Java 软件设计基础

School of Computer Science and Technology

–主要方法

–示例

String getText()String getText() 返回返回 LabelLabel 对象文本的对象文本的 StringString

setText(String s)setText(String s) 设置设置 LabelLabel 对象的文字对象的文字

setAlignment(int align)setAlignment(int align) 设置设置 LabelLabel 对象的对齐方式对象的对齐方式

创建Label

import java.awt.*;public class Label1{

public static void main(String args[]){Frame f = new Frame("Label");Label myLabel1=new Label("This is a label");f.setBounds(0,0,280,220);myLabel1.setAlignment(Label.CENTER);myLabel1.setBackground(Color.pink);myLabel1.setForeground(Color.blue);f.add(myLabel1);f.setVisible(true);

}}

Page 19: Java 软件设计基础

School of Computer Science and Technology

• TextField——TextField—— 文本框和文本框和 TextArea——TextArea—— 文本域文本域–它们都是 TextComponent的子类,用于文本处理。–TextField

•文本框是单行文本输入域,多用于单行显示。•当按下 回 车键时,会发生事件 (ActionEvent) ,可以通过

ActionListener中的 actionPerformed方法对事件进行处理。•构造方法

–创建一个初始文本串为空的文本框对象

–创建一个初始文本串为 str的文本框对象

–创建一个初始文本串为 str、列数为 column 长度的文本框对象

TextField()TextField()

TextField(String str)TextField(String str)

TextField(String str, int column)TextField(String str, int column)

Page 20: Java 软件设计基础

School of Computer Science and Technology

•主要方法

–TextArea•是多行文本组件,用于显示程序中的多行文本信息。•构造方法

–创建一个初始文本串为 str的文本域对象

–创建 numLines行、 numChars列的文本域对象

–创建一个初始文本串为 str、 numLines行、 numChars列的文本域对象

setText(String s)setText(String s) 将文本框对象的文本信息设置为将文本框对象的文本信息设置为 strstr

getText()getText() 返回文本框对象的文本信息返回文本框对象的文本信息

getSelectedText()getSelectedText() 返回文本框对象被选的文本串信息内容返回文本框对象被选的文本串信息内容

setEchoChar(char ch)setEchoChar(char ch) 将文本框对象的回显字符设为将文本框对象的回显字符设为 chch ,常用于密码接收场合,常用于密码接收场合

TextArea(String str)TextArea(String str)

TextArea(int numLines, int numChars)TextArea(int numLines, int numChars)

TextArea(String str, int numLines, int numChars)TextArea(String str, int numLines, int numChars)

Page 21: Java 软件设计基础

School of Computer Science and Technology

•主要方法

–示例:

setText(String s)setText(String s) 将文本域对象的文本信息设置为将文本域对象的文本信息设置为 strstr

getText()getText() 返回文本域对象的文本信息返回文本域对象的文本信息

文本框与文本域import java.awt.*;public class Login{

public static void main(String args[]){Frame f = new Frame("User login");f.setBounds(0,0,400,300);f.setBackground(Color.lightGray);f.setLayout(null);Label l1 = new Label("User:"); Label l2 = new Label("Password:");TextField t1 = new TextField("user1",20); TextField t2 = new TextField(20);t2.setEchoChar('*');Button b1=new Button("Confirm"); Button b2=new Button("Cancel");TextArea ta=new TextArea("Edit your basic information:",5,20);l1.setBounds(50,50,50,20); l2.setBounds(50,80,50,20);t1.setBounds(100,50,180,20); t2.setBounds(100,80,180,20);b1.setBounds(70,110,50,20); b2.setBounds(200,110,50,20);ta.setBounds(50,140,230,80);f.add(l1); f.add(l2); f.add(t1); f.add(t2); f.add(ta); f.add(b1); f.add(b2);f.setVisible(true);

}}

Page 22: Java 软件设计基础

School of Computer Science and Technology

Page 23: Java 软件设计基础

School of Computer Science and Technology

• 复选框与单选按钮复选框与单选按钮–简介

•复 选 框 又 称 为 检 测 盒 , 用 Checkbox 类 的 对 象 表示, Checkbox 由一个方形的选择 区和一个标签组成,有选中(check)和未选中 (uncheck) 两种状态。

•单独的 Checkbox实现的是复选框功能,当多个 Checkbox 加入到一个 CheckboxGroup组件内时,选择区变成圆形,组件内的Checkbox只能有一个被选中,此时实现的是单选按钮的功能。

•复选框和单选框使用 ItemListener来监听 ItemEvent事件。–构造方法

•创建一个标签为 str的复选框

•创 建 一 个 标 签 为 str 的 单 选 按 钮 , g 指 明 所 属 的CheckboxGroup

Checkbox(String str)Checkbox(String str)

Checkbox(String str, CheckboxGroup g, boolean state)Checkbox(String str, CheckboxGroup g, boolean state)

Page 24: Java 软件设计基础

School of Computer Science and Technology

–主要方法getState()getState() 返回返回 CheckboxCheckbox 对象的状态是否被选中对象的状态是否被选中

setStateChange()setStateChange() 获取获取 CheckboxCheckbox 对象的当前状态对象的当前状态

setState(boolean state)setState(boolean state) 设置设置 CheckboxCheckbox 对象的状态对象的状态单选复选

import java.awt.*;public class CheBox{

public static void main(String args[]){Frame f = new Frame("Checkbox and CheckboxGroup");Label l = new Label("Your favorite sports:");Checkbox cb1 = new Checkbox("Tennis");Checkbox cb2 = new Checkbox("Football");Checkbox cb3 = new Checkbox("Swimming");CheckboxGroup cbg = new CheckboxGroup();

Checkbox cb4 = new Checkbox("Male",cbg,true);Checkbox cb5 = new Checkbox("Female",cbg,false);

f.setLayout(null); f.setSize(200,150);l.setBounds(10,40,140,20); cb1.setBounds(150,40,140,20);cb2.setBounds(150,60,140,20); cb3.setBounds(150,80,140,20);cb4.setBounds(150,100,140,20); cb5.setBounds(150,120,140,20);f.add(l); f.add(cb1); f.add(cb2);f.add(cb3); f.add(cb4); f.add(cb5);f.setVisible(true);

}}

Page 25: Java 软件设计基础

School of Computer Science and Technology

• Choice——Choice—— 下拉列表下拉列表–简介

•提供一个弹出式的菜单让用户选择,也是“多选一”的输入界面。•与单选按钮组利用单选按钮把所有选项列出的方法不同,下拉列表

的所有选项被折叠起来,在这个菜单折叠时只显示最前面的或是用户选定的那一项。

•下拉列表节省显示空间,适用于大量选项的情形。•Choice用 ItemListener接口来监听。

–构造方法•创建一个空白的下拉列表Choice()Choice()

Page 26: Java 软件设计基础

School of Computer Science and Technology

–主要方法

• List——List——列表列表–简介

•把所有供用户选择的项都显示出来以供选择。•列表可以实现多选,支持滚动条,可以同时浏览多项。•列表可以产生两种事件:

addItem(String item)addItem(String item) 添加一个添加一个 itemitem 字符串到字符串到 ChoiceChoice 对象中对象中

add(String item)add(String item) 将新选项将新选项 itemitem 加载当前下拉列表的最后加载当前下拉列表的最后

getSelectedIndex()getSelectedIndex() 返回被选中的选项的序号返回被选中的选项的序号 (0~n-1)(0~n-1)

getItem(int index)getItem(int index) 返回返回 ChoiceChoice 对象对象 indexindex 索引项目的字符串索引项目的字符串

getSelectedItem()getSelectedItem() 返回返回 ChoiceChoice 对象所选项目的字符串对象所选项目的字符串

removeAll()removeAll() 把下拉列表中的选项全部移除把下拉列表中的选项全部移除

remove(String item)remove(String item) 把指定标签文本的选项移除把指定标签文本的选项移除

Page 27: Java 软件设计基础

School of Computer Science and Technology

–当用户单击列表中的某一个选项并选中它时,将产生 ItemEvent类的选择事件;–当用户双击列表中的某一个选项时,将产生 ActionEvent类的动作事件。

–构造方法•建立行数为 rows的 List对象,参数 b 为真时允许多选

–主要方法

List(int rows, boolean b)List(int rows, boolean b)

getSelectedItem()getSelectedItem() 返回返回 ListList 对象所选项目的字符串组成的字符串数组对象所选项目的字符串组成的字符串数组

getSelectedIndex()getSelectedIndex() 返回被选中的选项的序号返回被选中的选项的序号 (0~n-1)(0~n-1) 组成的整数数组组成的整数数组

addItem(String item, int addItem(String item, int index)index)

添加一个添加一个 itemitem 字符串到字符串到 ListList 对象的索引对象的索引 indexindex 处处

delItem(int index)delItem(int index) 删除删除 ListList 对象对象 indexindex 处的选项处的选项

add(String item)add(String item) 将新选项将新选项 itemitem 加载当前列表的最后加载当前列表的最后

remove(String item)remove(String item) 把指定标签文本的选项移除把指定标签文本的选项移除

Page 28: Java 软件设计基础

School of Computer Science and Technology

–示例单选复选

import java.awt.*;import java.awt.event.*;public class ChoiceList{

private ChoiceList(){Frame f = new Frame("Choice and List");f.setLayout(new GridLayout(2,3,25,25));Choice ch = new Choice();

ch.addItem("Male");ch.addItem("Female");

f.add(ch);List l=new List(3,true);

l.addItem("Tennis");l.addItem("Football");l.addItem("Swimming");

f.add(l);f.setSize(250,150);f.setVisible(true);

}public static void main(String args[]){

ChoiceList cl = new ChoiceList();}

}

Page 29: Java 软件设计基础

School of Computer Science and Technology

• Dialog——Dialog——对话框对话框–简介

•对话框与框架类似,是有边框、有标题而独立存在的容器。通常起到与用户交互的对话窗口的作用。

•对话框不能作为程序的最外层容器,也不能包含菜单栏,它必须隶属于某个框架并由该框架负责弹出。

•对话框可以被设置为模式窗口,其特点是总是在激活窗口的最前面,即若是不关闭,则不能对其他窗口进行操作。

–构造方法•创建没有标题的对话框,Owner表示所有者

•创建有指定标题 title的对话框

•创建指定标题的对话框并指明是否为模式窗口

Dialog(Frame Owner)Dialog(Frame Owner)

Dialog(Frame Owner, String title)Dialog(Frame Owner, String title)

Dialog(Frame Owner, String title, boolean model)Dialog(Frame Owner, String title, boolean model)

Page 30: Java 软件设计基础

School of Computer Science and Technology

–主要方法

–示例

setTitle(String title)setTitle(String title) 将对话框对象的标题设置为将对话框对象的标题设置为 titletitle

getTitle()getTitle() 返回对话框对象的标题返回对话框对象的标题

setVisible(boolean f)setVisible(boolean f) 设置对话框对象的标题是否显示设置对话框对象的标题是否显示

setModel(boolean f)setModel(boolean f) 设置对话框模式是否为模式窗口设置对话框模式是否为模式窗口对话框

import java.awt.*;public class Dlog{

Frame f = new Frame("Dialog owner");Dialog d = new Dialog(f,"This is a Dialog Window",false);Button b = new Button("Confirm");Label l = new Label("welcome");public void go(){

f.setBounds(50,50,230,180); f.setLayout(null);b.setBounds(50,100,50,20); f.add(b);d.setBounds(50,100,250,150); d.setLayout(null);l.setBounds(90,70,150,20); d.add(l);f.setVisible(true); d.setVisible(true);

}public static void main(String args[]){

Dlog e = new Dlog(); e.go();}

}

Page 31: Java 软件设计基础

School of Computer Science and Technology

对话框import java.awt.*;import java.awt.event.*;public class Dlog implements ActionListener{

Frame f = new Frame("Dialog owner");Dialog d = new Dialog(f,"This is a Dialog Window",false);Button b = new Button("Confirm");Label l = new Label("welcome");public void go(){

f.setBounds(50,50,230,180);f.setLayout(null);f.add(b);b.setBounds(50,100,50,20);d.add(l);d.setLayout(null);d.setBounds(50,100,250,150);l.setBounds(90,70,150,20);b.addActionListener(this);f.setVisible(true);

}public void actionPerformed(ActionEvent e){

d.setVisible(true);}public static void main(String args[]){

Dlog e = new Dlog();e.go();

}}

Page 32: Java 软件设计基础

School of Computer Science and Technology

画布import java.awt.*;import java.awt.event.*;import java.util.*;public class CanvasExample implements KeyListener,MouseListener{

Canvas c;TextField t;public static void main(String args[]){

Frame f = new Frame("Canvas Example");CanvasExample mc = new CanvasExample();mc.c = new Canvas();mc.t = new TextField();f.add("South",mc.t); f.add("Center",mc.c);f.setSize(300,200);f.setBackground(Color.pink); f.setForeground(Color.blue);mc.c.addMouseListener(mc);mc.c.addKeyListener(mc);f.setVisible(true);

}实现各个接口的方法;

}

• Canvas——Canvas——画布画布–画布代表屏幕上一块空白的矩形区域,它不是容器,而是一个可以在这里绘画、捕捉用户操作、产生相应事件的区域。

Page 33: Java 软件设计基础

School of Computer Science and Technology

3. 事件处理机制

• 事件处理基础事件处理基础–事件及其处理机制

•GUI的两大任务–创建窗口并在窗口中添加各种组件,规划组件在窗口中的位置和相关属性,构成GUI的外观效果;–设置各类组件对不同事件的响应,从而执行用户在用户界面所实施的交互行为,如果用户在用户界面执行了一个动作,这将导致一个事件的发生。

•事件是描述用户所执行的一个操作、所产生的一个行为,主要涉及以下三个概念:

–事件 (Event):用来描述在用户界面的用户交互行为所产生的一种效果;–事件源 (Event Source):产生事件的组件对象;–事件处理方法 (Event Handler):负责解析处理事件的类对象,用以实现和用户交互的方法。

Page 34: Java 软件设计基础

School of Computer Science and Technology

•事件的类层次

–事 件 处 理 方 法 主 要 基 于 “ 事 件 授 权 模 型 ” (EDM: Event Delegation Model)的处理机制,实现定义多种事件类型。–事件源拥有自己的方法,通过它可以向其注册事件监听器。事件监听器是一个实例,当事件源产生一个事件后,事件源就会通知相应的事件监听器,根据事件对象内封装的消息决定如何响应该事件。–一个事件源可以注册一个或多个监听器,一个监听器也可以被注册到多个事件源。

ComponentEvent

ItemEvent

TextEvent

AdjustmentEvent

ActionEvent

PrintEvent

InputEvent

WindowEvent

FocusEvent

ContainerEvent

KeyEvent

MouseEventjava.awt.AWTEvent

java.util.EventObject

Page 35: Java 软件设计基础

School of Computer Science and Technology

–事件的接口及方法•ActionEvent

–行为:点击按钮、文本框、列表及选择菜单等–接口名: ActionListener–注册方法:–监听器接口所提供的事件方法:

•ItemEvent–行为:点击复选框选择框列表及带复选框的菜单项等–接口名: ItemListener–注册方法:–监听器接口所提供的事件方法

•KeyEvent–行为:按下或释放键盘

addActionListener(ActionListener Listener)addActionListener(ActionListener Listener)

actionPerformed(ActionEvent e)actionPerformed(ActionEvent e)

addItemListener(ItemListener Listener)addItemListener(ItemListener Listener)

itemStateChanged(ItemEvent e)itemStateChanged(ItemEvent e)

Page 36: Java 软件设计基础

School of Computer Science and Technology

–接口名: KeyListener–注册方法:–监听器接口所提供的事件方法

•MouseEvent–行为:鼠标单击或鼠标移动–接口名:

»鼠标单击: MouseListener»鼠标移动: MouseMotionListener

–注册方法:»鼠标单击:»鼠标移动:

addKeyListener(KeyListener Listener)addKeyListener(KeyListener Listener)

keyPressed(KeyEvent e)keyPressed(KeyEvent e)

keyReleased(KeyEvent e)keyReleased(KeyEvent e)

keyTyped(KeyEvent e)keyTyped(KeyEvent e)

getModified()getModified()

addMouseListener(MouseListener Listener)addMouseListener(MouseListener Listener)

addMouseMotionListener(MouseMotionListener Listener)addMouseMotionListener(MouseMotionListener Listener)

Page 37: Java 软件设计基础

School of Computer Science and Technology

–监听器接口所提供的事件方法:»鼠标单击

»鼠标移动

•WindowEvent–行为:激活、打开、关闭窗口或窗口失去焦点及收到窗口级事件–接口名:WindowListener–注册方法:

mousePressed(MouseEvent e)mousePressed(MouseEvent e)

mouseReleased(MouseEvent e)mouseReleased(MouseEvent e)

mouseEntered (MouseEvent e)mouseEntered (MouseEvent e)

mouseExited(MouseEvent e)mouseExited(MouseEvent e)

mouseClicked(MouseEvent e)mouseClicked(MouseEvent e)

mouseMoved(MouseEvent e)mouseMoved(MouseEvent e)

mouseDragged(MouseEvent e)mouseDragged(MouseEvent e)

addWindowListener(WindowListener Listener)addWindowListener(WindowListener Listener)

Page 38: Java 软件设计基础

School of Computer Science and Technology

–监听器接口所提供的事件方法:

•TextEvent–行为:文本框、文本域发生改变–接口名: TextListener–注册方法:–监听器接口所提供的事件方法:

windowClosing(WindowEvent e)windowClosing(WindowEvent e)

windowClosed(WindowEvent e)windowClosed(WindowEvent e)

windowOpened(WindowEvent e)windowOpened(WindowEvent e)

windowIconified(WindowEvent e)windowIconified(WindowEvent e)

windowDeiconified(WindowEvent e)windowDeiconified(WindowEvent e)

windowActivated(WindowEvent e)windowActivated(WindowEvent e)

windowDeactivated(WindowEvent e)windowDeactivated(WindowEvent e)

addTextListener(TextListener Listener)addTextListener(TextListener Listener)

textValueChanged(TextEvent e)textValueChanged(TextEvent e)

Page 39: Java 软件设计基础

School of Computer Science and Technology

•FocusEvent–行为:组件获得或失去焦点–接口名: FocusListener–注册方法:–监听器接口所提供的事件方法:

•ComponentEvent–行为:移动、隐藏、显示组件和改变组件大小等。–接口名: ComponentListener–注册方法:–监听器接口所提供的事件方法:

addComponentListener(监听者 )addComponentListener(监听者 )

ComponentMoved(ComponentEvent e)ComponentMoved(ComponentEvent e)ComponentHidden(ComponentEvent e)ComponentHidden(ComponentEvent e)ComponentResized(ComponentEvent e)ComponentResized(ComponentEvent e)

ComponentShown(ComponentEvent e)ComponentShown(ComponentEvent e)

addFocusListener(FocusListener Listener)addFocusListener(FocusListener Listener)

FocusGained(FocusEvent e)FocusGained(FocusEvent e)

FocusLost(FocusEvent e)FocusLost(FocusEvent e)

Page 40: Java 软件设计基础

School of Computer Science and Technology

•ContainerEvent–行为:添加、移动组件等–接口名: ContainerListener–注册方法:–监听器接口所提供的事件方法:

•AdjustmentEvent–行为:调节滚动条或滑块等–接口名: AdjustmentListener–注册方法:–监听器接口所提供的事件方法:

addContainerListener(监听者 )addContainerListener(监听者 )

ContainerAdded(ContainerEvent e)ContainerAdded(ContainerEvent e)

ContainerRemoved(ContainerEvent e)ContainerRemoved(ContainerEvent e)

addAdjustmentListener(监听者 )addAdjustmentListener(监听者 )

AdjustmentValueChange(AdjustmentEvent e)AdjustmentValueChange(AdjustmentEvent e)

Page 41: Java 软件设计基础

School of Computer Science and Technology

–Java 针对大多数事件监听器接口定义了相应的实现类来实现接口中的所有方法。

• 事件处理主要步骤事件处理主要步骤–步骤:

•选择组件作为事件源,不同类型的组件会产生特定类型的事件,假设该事件类型为 XXXEvent;

•定义要接收并处理某种类型的事件,注册相应的事件监听器类,通过调用组件方法向组件注册事件监听器。

•实现 XXXListener类的实例对象,据此可作为事件的监听器对象。监听器的注册与注销如下:

eventsourceObject.addXXXListener(XXXListener Listener);eventsourceObject.addXXXListener(XXXListener Listener);

public void addXXXListener(XXXListener listener);public void addXXXListener(XXXListener listener);

public void removeXXXListener(XXXListener listener);public void removeXXXListener(XXXListener listener);

Page 42: Java 软件设计基础

School of Computer Science and Technology

•事件源通过实例化事件类激发并产生事件,事件将被传送给已注册的一个或多个监听器。监听器在接收到激发事件信号后负责实现相应的事件处理方法。

–以按钮组件作为事件源的简单范例•选择按钮组件作为事件源:

•定义要接受并处理的事件 ActionEvent,通过下面的语句注册事件监听器:

•按下按钮组件 bton对象会产生一个 ActionEvent实例对象,事件源通过实例化事件类激发事件并传送给已注册的监听器;

•监听器对象 listener所属的类MyActionListener需通过方法actionPerformed实现相应的接口以响应事件:

J Button bton = new J Button(“按钮”);/ /或者是下面的语句Button bton = new Button(“按钮”);

bton.addEventListener(listener);

public class MyActionListener implements ActionListener{……public void actionPerformed(ActionEvent e){相关操作;}

}

Page 43: Java 软件设计基础

School of Computer Science and Technology

• 键盘事件键盘事件–KeyEvent类在 java.awt.event包中,提供的主要方法:

•getKeyChar():判断被按下的键的字符;•getKeyCode():判断哪个键被按下、点击或释放并获取其键码

值。–Java 语言的部分键码表键码键码 键键 键码键码 键键

VK_CANCEL/CLEAR/COMMAVK_CANCEL/CLEAR/COMMA 取消取消 // 清除清除 // 逗号逗号 VK_F1~VK_F2VK_F1~VK_F2 F1~F12F1~F12

VK_UNMPAD0~VK_UNMPAD9VK_UNMPAD0~VK_UNMPAD9 小键盘小键盘 0~90~9 VK_0~VK_9VK_0~VK_9 0~90~9

VK_LEFT/RIGHT/UP/DOWNVK_LEFT/RIGHT/UP/DOWN 左右上下键左右上下键 VK_A~VK_ZVK_A~VK_Z a~za~z

VK_KP_LEFT/RIGHT/UP/DOWNVK_KP_LEFT/RIGHT/UP/DOWN 小键盘左右上下键小键盘左右上下键 VK_HOME/ENDVK_HOME/END HOME/ENDHOME/END

VK_BACK_SLASH/QUOTEVK_BACK_SLASH/QUOTE ““\”/\”/ 单引号单引号 VK_CAPS_LOCKVK_CAPS_LOCK 大写锁定大写锁定

VK_ALT/CONTROL/SHIFT/VK_ALT/CONTROL/SHIFT/ESCAPEESCAPE

Alt/Ctrl/Shift/Alt/Ctrl/Shift/EscEsc

VK_NUM_LOCKVK_NUM_LOCK 数字锁定数字锁定

VK_SEMICOLON/PERIOD/VK_SEMICOLON/PERIOD/SLASHSLASH

分号分号 //点点 /“/”/“/” VK_SPACE/TABVK_SPACE/TAB 空格空格 //制表符制表符

VK_OPEN/CLOSE_BRACKETVK_OPEN/CLOSE_BRACKET [/][/] VK_QUOTEVK_QUOTE 单引号单引号

VK_INSERT/DELETE/ENTER/VK_INSERT/DELETE/ENTER/PAUSEPAUSE

插入插入 // 删除删除 // 回车回车 //暂停暂停

VK_PAGE_UP/DOWNVK_PAGE_UP/DOWN 前后翻页前后翻页

Page 44: Java 软件设计基础

School of Computer Science and Technology

–简单键盘事件的使用•组件使用 addKeyListener() 方法获得监视器。监视器是一个

对象,创建该对象的类必然通过以下三种方法来实现接口:–public void keyPressed(KeyEvent e);

»按下键盘上的某个键–public void keyTyped(KeyEvent e);

»当键被按下又释放–public void KeyReleased(KeyEvent e);

»释放键盘上的某个键•示例:将键盘输入字符的键码、名称和按键显示出来。

–设置用来显示的面板:

class KeyPanel extends J panel implements keyListener{public char KeyChar;public int KeyInputCode;public String KeyText;public boolean isChar=false;

}

Page 45: Java 软件设计基础

School of Computer Science and Technology

–注册键盘事件监听器

–允许面板获得焦点

–对键盘事件进行响应(即实现接口方法)

public KeyPanel(){addKeyListener(this);

}

public void keyPressed(KeyEvent e){KeyInputCode=e.getKeyCode();

}public void keyReleased(KeyEvent e){

KeyInputCode = e.getKeyCode();KeyText = e.getKeyText(KeyInputCode);if(!isChar){

KeyChar=' ';}isChar=false;repaint();

}public void keyTyped(KeyEvent e){

KeyChar = e.getKeyChar();isChar = true;

}

public void keyPressed(KeyEvent e){KeyInputCode=e.getKeyCode();

}

Page 46: Java 软件设计基础

School of Computer Science and Technology

–键盘释放时重绘窗口:

–将 KeyPanel实例加入到容器中:

public void paintComponent(Graphics g){super.paintComponent(g);if(KeyInputCode==-1)

g.drawString("InputKeyCode:",90,70);else

g.drawString("InputKeyCode:"+KeyInputCode,90,70);g.drawString("KeyText:"+KeyText,90,90);g.drawString("KeyChar:"+KeyChar,90,110);

}

class KeyFrame extends J Frame{public KeyFrame(){

setTitle("input and display the char from keyboard");setSize(280,190);KeyPanel panel = new KeyPanel();Container contentPane = getContentPane();panel.setBackground(Color.pink);contentPane.add(panel);

}}

Page 47: Java 软件设计基础

School of Computer Science and Technology

Page 48: Java 软件设计基础

School of Computer Science and Technology

–复合键盘事件的使用•KeyEvent类对象可调用 getModifiers()方法返回以下整数值:

–CTRL_MASK–ALT_MASK–SHIFT_MASK

•以上是 InputEvent类的类常量,根据返回值对复合键事件做处理。

–当使用 Ctrl+C复合键时,下面的逻辑表达式为真:

•示例:利用对组合键事件的响应来处理复制、剪切与粘贴–对复制、剪切、粘贴的处理

e.getModifiers()==InputEvent.CTRL_MASK&&e.getKeyCode()==KeyEvent.VK_C

public void keyTyped(KeyEvent e){J TextArea te=(J TextArea)e.getSource();if(e.getModifiers()==InputEvent.CTRL_MASK&&e.getKeyCode())==KeyEvent.VK_X){te.cut();}else if(e.getModifiers()==InputEvent.CTRL_MASK&&e.getKeyCode())==KeyEvent.VK_C){te.copy();}else if(e.getModifiers()==InputEvent.CTRL_MASK&&e.getKeyCode())==KeyEvent.VK_P){te.paste();}

}

Page 49: Java 软件设计基础

School of Computer Science and Technology

class Win extends J Frame implements KeyListener{Win(){

Container con = getContentPane();con.setLayout(new FlowLayout());J TextArea text= new J TextArea(15,20);con.add(new J ScrollPane(text),BorderLayout.CENTER);text.addKeyListener(this);text.setBackground(Color.pink);text.setForeground(Color.blue);setTitle("combination key");setBounds(10,10,300,300);setVisible(true);validate();

}

–窗口组件安放:

Page 50: Java 软件设计基础

School of Computer Science and Technology

• 文本事件文本事件–TextArea或 TextField信息发生改变时会触发 TextEvent事件。需要在程序中将 TextEvent 事件注 册给监 听器TextListener , 并 实 现 TextListener 接 口 中 的textValueChanged方法。

–示例:改变 TextArea中的文字,并在标签中回显•安放组件,并注册监听器:class Text implements TextListener{

String str="";Frame f = new Frame();TextArea ta = new TextArea(3,20);Label l=new Label("text not changed");Text(){

f.setBounds(0,0,300,200);f.setLayout(null);l.setBounds(20,30,200,20);ta.setBounds(20,50,200,100);f.add(l);f.add(ta);f.setVisible(true);ta.addTextListener(this);

}

Page 51: Java 软件设计基础

School of Computer Science and Technology

•响应文本事件(即实现接口方法)单选复选

public void textValueChanged(TextEvent e){str="text changes to:"+ta.getText();l.setText(str);f.validate();

}

Page 52: Java 软件设计基础

School of Computer Science and Technology

• 鼠标事件鼠标事件–MouseListener

•触发鼠标事件的四种操作:–鼠标指针进入组件或退出组件

»mouseEntered(MouseEvent e)»mouseExited(MouseEvent e)

–鼠标指针停留在组件上时按下鼠标»mousePressed(MouseEvent e)

–鼠标指针停留在组件上时释放鼠标»mouseReleased(MouseEvent e)

–鼠标指针停留在组件上时单击或连续单击鼠标»mouseClicked(MouseEvent e)

–MouseMotionListener•触发鼠标事件的两种操作:

–在组件上拖动鼠标指针

Page 53: Java 软件设计基础

School of Computer Science and Technology

»mouseDragged(MouseEvent e)

–在组件上运动鼠标指针»mouseMoved(MouseEvent e)

–由于处理鼠标事件的接口中的方法较多, Java提供了相应的适配器类 MouseAdapter 和 MouseMotionAdapter ,据此分别实现了MouseListener接口和MouseMotionListener。

–获取鼠标的具体信息的方法:

getX()getX() 返回鼠标事件发生时坐标点的返回鼠标事件发生时坐标点的 xx 值值

getY()getY() 返回鼠标事件发生时坐标点的返回鼠标事件发生时坐标点的 yy 值值

getSource()getSource() 返回触发当前鼠标事件的事件源返回触发当前鼠标事件的事件源

getPointer()getPointer() 返回鼠标事件发生时的坐标点返回鼠标事件发生时的坐标点 (Point(Point 类型类型 ))

getClickCount()getClickCount() 返回鼠标被连续点击的次数返回鼠标被连续点击的次数

getModifiers()getModifiers() 如果是鼠标左键触发,则返回值为如果是鼠标左键触发,则返回值为 BUTTON1_MASKBUTTON1_MASK ;如果是鼠标右;如果是鼠标右键触发,则返回值为键触发,则返回值为 BUTTON3_MASKBUTTON3_MASK ,以上两个整数值都是,以上两个整数值都是InputEventInputEvent 中的类常量中的类常量

Page 54: Java 软件设计基础

School of Computer Science and Technology

–示例:当鼠标发生事件时在窗口显示事件并给出鼠标位置。•处理鼠标事件(即实现接口方法)

public class MouseWork extends J Frame implements MouseListener,MouseMotionListener{public void mouseClicked(MouseEvent e){

status.setText("Mouse Clicked["+e.getX()+","+e.getY()+"]");}public void mousePressed(MouseEvent e){

status.setText("Mouse Pressed["+e.getX()+","+e.getY()+"]");}public void mouseReleased(MouseEvent e){

status.setText("Mouse Released["+e.getX()+","+e.getY()+"]");}public void mouseEntered(MouseEvent e){

status.setText("Mouse Entered");}public void mouseExited(MouseEvent e){

status.setText("Mouse Exited");}public void mouseMoved(MouseEvent e){

status.setText("Mouse Moved["+e.getX()+","+e.getY()+"]");}public void mouseDragged(MouseEvent e){

status.setText("Mouse Dragged["+e.getX()+","+e.getY()+"]");}

}

Page 55: Java 软件设计基础

School of Computer Science and Technology

•构造窗口

•注册监听器

private J Label status;public MouseWork(){

super("Mouse Action Example");status = new J Label();status.setFont(new Font("Arial",Font.BOLD,20));getContentPane().add(status,BorderLayout.SOUTH);setSize(275,100);show();

}

addMouseListener(this);addMouseMotionListener(this);

Page 56: Java 软件设计基础

School of Computer Science and Technology

–获取鼠标在系统桌面上的坐标•PointerInfo类可以帮助程序获得鼠标指针在系统图形设备中的

位置坐标。•PointerInfo类中的类方法:

–getPointerInfo():可通过以下语句实例化一个 PointerInfo对象

–getLocation() :返回一个 Point 对象,对象通过调用 getX() 和getY()方法返回鼠标在桌面上的坐标值。

•当 鼠 标 运 动 时 必 须 及 时 更 新 PointerInfo 对象,因为PointerInfo对象中存储的 Point对象不会自动更新。

–弹出式菜单•通过 JPopupMenu类负责创建

–构造无标题弹出式菜单public JpopupMenu()public JpopupMenu()

PointerInfo pi = MouseInfo.getPointerInfo();

Page 57: Java 软件设计基础

School of Computer Science and Technology

–构造由参数 label指定标题的弹出式菜单

•设置弹出式菜单在组件上的弹出位置:

• 窗口事件窗口事件–当一个窗口 (Frame或 JFrame)被激活、撤销、打开、关闭、图 标 化 等 操 作 时 , 会 引 发 WindowEvent 事 件 。 方 法getWindow()用来获取发生窗口事件的窗口。

–触发窗口事件•当单击窗口的图标化按钮时,监视器要调用以下两种方法:

–WindowIconified()–WindowDeactivated()

•当撤销窗口图标化时,监视器要调用以下两种方法:–WindowDeiconified()–WindowActivated()

public JpopupMenu(String label)public JpopupMenu(String label)

public void show(Component c, int x, int y);

Page 58: Java 软件设计基础

School of Computer Science and Technology

–示例import java.awt.*;import java.awt.event.*;import javax.swing.*;public class WinExample{

public static void main(String args[]){MyWindowEvent win = new MyWindowEvent("Windows event");

}}class MyWindowEvent extends J Frame implements WindowListener{

J Button b;MyWindowEvent(String s){

super(s);addWindowListener(this);b = new J Button("My Windows Button");Container con = getContentPane();con.setLayout(new FlowLayout());con.add(b);setBounds(150,100,150,150);setVisible(true);validate();

}public void windowClosing(WindowEvent e){System.exit(0);}public void windowIconified(WindowEvent e){b.setBackground(Color.yellow);}public void windowDeiconified(WindowEvent e){}public void windowClosed(WindowEvent e){}public void windowOpened(WindowEvent e){}public void windowActivated(WindowEvent e){}public void windowDeactivated(WindowEvent e){}

}

Page 59: Java 软件设计基础

School of Computer Science and Technology

• 焦点事件焦点事件–组件对象可以触发焦点事件,当组件具有焦点监视器后,如果组件从无输入焦点变成有输入焦点时,或从有输入焦点变成无输入焦点,都会触发 FocusEvent事件。

–方法•获得输入焦点

•组件从无输入焦点变成有输入焦点时实现的接口方法–FocusGained(FocusEvent e)

•组件从有输入焦点变成无输入焦点时实现的接口方法–FocusLost(FocusEvent e)

–示例:在窗口中安放两个组件,检测对焦点事件的响应。

public boolean requestFocusInWindow()

Page 60: Java 软件设计基础

School of Computer Science and Technology

import java.awt.*;import java.awt.event.*;import javax.swing.*;public class FocusEx{

public static void main(String args[]){MyWindow mw=new MyWindow("Focus window");}}class MyWindow extends J Frame implements FocusListener{

MyWindow(String s){super(s);J TextField jt=new J TextField("Check Focus",18);J Button jb=new J Button("Focus Button");jt.requestFocusInWindow();Container con = getContentPane();con.setLayout(new FlowLayout());con.add(jt); con.add(jb);jt.addFocusListener(this); jb.addFocusListener(this);setBounds(100,100,250,150);setVisible(true);validate();setDefaultCloseOperation(J Frame.EXIT_ON_CLOSE);

}public void focusGained(FocusEvent e){

J Component com=(J Component)e.getSource();com.setBackground(Color.pink);

}public void focusLost(FocusEvent e){

J Component com=(J Component)e.getSource();com.setBackground(Color.blue);

}}

Page 61: Java 软件设计基础

School of Computer Science and Technology

Page 62: Java 软件设计基础

School of Computer Science and Technology

• 事件适配器事件适配器–Java 针对大多数事件监听器接口定义了相应的已经实现了接口

功能的实现类:事件适配器类。宗旨是使监听器的创建变得更加简便。

–适配器中系统自动实现相应监听器接口中的所有方法 ( 只写出空方法体 ) ,但不做任何事情。编程时定义继承事件适配器类的监听器,只重写需要的方法。常用的适配器类有:

•KeyAdapter:键盘事件适配器•MouseAdapter:鼠标事件适配器•MouseMotionAdapter:鼠标运行事件适配器•WindowAdapter:窗口事件适配器•FocusAdapter:焦点事件适配器•ComponentAdapter:组件事件适配器•ContainerAdapter:容器事件适配器

Page 63: Java 软件设计基础

School of Computer Science and Technology

–示例import java.awt.*;import java.awt.event.*;import javax.swing.*;public class WinAdapter{

public static void main(String args[]){Frame f=new Frame("Adapter");f.addWindowListener(new MyWindowListener());f.setLayout(new FlowLayout());f.setBounds(150,100,150,150);f.setBackground(Color.pink);f.setVisible(true);

}}class MyWindowListener extends WindowAdapter{

public void windowClosing(WindowEvent e){System.exit(0);

}}