Transcript Events

Object-Oriented Design and Programming (Java)
Topics Covered Today
• 3.2 Graphical User Interface
– 3.2.1 Swing Components and Containers
– 3.2.2 Swing Event Handling
2
GUI libraries in JAVA
• Abstract Windows Toolkit (AWT) since Java 1.0
• Swing - Add-on since Java 1.1 and integral part of
Java 1.2
• Third party GUI libraries like the Standard Windows
Toolkit (SWT) e.g. used in Eclipse
Here, we use Swing!
3
Swing is Standard in Java 2 Platform
(also known as JDK 1.2)
• Includes Java2D
• Adds support for MIDI, WAV, and other
audio.
• Swing package: javax.swing.*
AWT package: java.awt.*
4
Reference Book
• Thinking in Java (2nd Edition), Bruce
Eckel, Prentice Hall
Chapter 13 Creating Windows & Applets
• Getting Started with Swing
http://java.sun.com/docs/books/tutorial/uiswing/
5
New Features in Swing
• Lightweight. Not built on native window-system
windows.
• Much bigger set of built-in controls. Trees, image
buttons, tabbed panes, sliders, toolbars, color
choosers, tables, etc.
• Much more customizable(可定制). Can change
border, text alignment, or add image to almost any
control.
6
New Features in Swing
• Pluggable" look and feel. Can change look and
feel at runtime, or design own look and feel.
• Many miscellaneous new features. Doublebuffering built in, tool tips, keyboard accelerators,
custom cursors, etc.
7
AWT Components
primitive
container
8
Swing Components
9
Frame
• A Frame is a top-level window with a title and a
border.
10
Frame
import java.awt.*;
public class MyFrame extends Frame {
public static void main(String args[ ]) {
MyFrame fr = new MyFrame("Hello Out There");
fr.setSize(200,200);
fr.setBackground(Color.red);
fr.setVisible(true);
}
public MyFrame (String str) {
super(str);
}
}
11
Panel
• Panel is the simplest container class.
• A panel provides space in which an application
can attach any other component, including other
panels.
12
Panel
import java.awt.*;
public class FrameWithPanel extends Frame{
public FrameWithPanel(String str){
super(str);
}
public static void main(String args[]){
FrameWithPanel fr = new FrameWithPanel("Frame with Panel");
Panel pan = new Panel();
fr.setSize(200,200);
fr.setBackground(Color.red);
fr.setLayout(null);
pan.setSize(100,100);
pan.setBackground(Color.yellow);
fr.add(pan);// add pan to frame fr
fr.setVisible(true);
}
}
13
Layout Managers
• Associated with containers
• Automate the layout of elements
– When elements are added to the container
– When the window is resized
• automatically adjust the positions and sizes of the elements.
14
Hierarchy of Layout Managers
Q: Can you identify the design pattern used here?
15
BorderLayout
• A border layout arranges and resizes container’s
components to fit in five regions: north, south, east, west,
and center.
• Each region may contain no more than one component
16
BorderLayout Example
import java.awt.*;
public class buttonDir{
public static void main(String args[]){
Frame f = new Frame("BorderLayout");
f.setLayout(new BorderLayout());
f.add("North", new Button("North"));
f.add("South", new Button("South"));
f.add("East", new Button("East"));
f.add("West", new Button("West"));
f.add("Center", new Button("Center"));
f.setSize(200,200);
f.setVisible(true);
}
}
17
GridLayout
• The GridLayout class is a layout manager that lays
out a container's components in a rectangular grid.
18
GridLayout
import java.awt.*;
public class ButtonGrid {
public static void main(String args[]) {
Frame f = new Frame("GridLayout");
f.setLayout(new GridLayout(3,2)); //3 rows & 2 columns
f.add(new Button("1"));
f.add(new Button("2"));
f.add(new Button("3"));
f.add(new Button("4"));
f.add(new Button("5"));
f.add(new Button("6"));
f.setSize(200,200);
f.setVisible(true);
}
}
19
JLable
• A JLabel can display both text and images
• Example:
JLabelDemo.java in Unit 3.2.1
20
JButton
• A JButton can not only display both text and image in the
form of button, but also respond to an event triggered by
users.
• Example:
JButtonDemo.java in Unit 3.2.1
21
JRadioButton
• Components of class JRadioButton can be selected
or deselected by the user. If JRadioButton
components are grouped, by means of the class
ButtonGroup, only one button at a time can be
selected.
• Example:
JRadioButtonDemo.java in Unit 3.2.1
22
JTextField
• Components of class JTextField let the user enter
(or edit) a small quantity of text.
• Example:
JTextFieldDemo.java in Unit 3.2.1
23
JTextArea
• Components of class JTextArea let the user enter (or edit)
multiple lines of text. If scroll bars are needed, the
JTextArea is wrapped in a JScrollPane.
• Example:
JTextAreaDemo.java in Unit 3.2.1
24
JList
• Components of class JList let the user select one or
more elements from a list. If scroll bars are needed,
the JList is wrapped in a JScrollPane.
• Example:
JListDemo.java in Unit 3.2.1
25
Back to the Buttons
• You click buttons and they don’t do anything!
• Well, what should they do? Java doesn’t know!
• Capture the event that a button has been clicked, and write
code to carry out the reaction.
• Any Swing component (like JButton) can report any or
all the things that happen to it.
26
Some Events and the Associated Event Listeners
Act that Results in the Event
Listener Type
User clicks a button, presses Enter while typing
in a text field, or chooses a menu item
ActionListener
User closes a frame (main window)
WindowListener
User presses a mouse button while the cursor is
over a component
MouseListener
User moves the mouse over a component
MouseMotionListener
Component becomes visible
ComponentListener
Component gets the keyboard focus
FocusListener
Table or list selection changes
ListSelectionListener
Any property in a component changes such as
the text on a label
PropertyChangeListener
27
ActionListener Model
Every event handler requires three pieces of code:
• A listener implements a listener interface or extends a class that
implements a listener interface. For example:
class ListenerOne implements ActionListener
• Registers an instance of the event listener class on one or more
components. For example:
component.addActionListener(
new ListenerOne());
• The event listener class implements the methods in the listener interface.
For example:
public void actionPerformed(ActionEvent e)
28
ButtonEventsDemo
• This demo contains 3
JRadioButtons and a JLabel.
When a user clicks one of the
radio buttons, the text in the
label is updated. Only one radio
button can be selected at a time
because the radio buttons are
grouped.
29
FruitListDemo
• This demo uses 3 components: a
JList, a JTextArea, and a JButton.
The JList contains a list of fruits
and the JTextArea is initially
empty.
ListSelectionListener/valueChanged()
30
GUI principles
GUI principles
Basic interacting objects supporting GUI
• Components: GUI building blocks.
buttons, menus, labels, etc.
• Events: reacting to user input.
button clicks, menu selections, etc.
• Layout: arranging components to form a usable GUI.
layout managers.
31
Design Pattern - MVC
• Model: the application object
• View: its screen presentation
• Controller: defines the way the user interface reacts to
user input.
Views
Controller
not shown
A = 30%
B = 20%
C = 50%
32
Model
Model-View-Controller
View
Get
Data
User Actions
State
Change
Notification
Model
Controller
Call Model
Action
Model
•
Encapsulates Data presented by view
View
•
Renders Model Data
Controller
•
Model Controller
•
View Controller
•
Responds to user actions
Model is loosely coupled from view
•
State change communicated through
notification.
•
Multiple views can be implemented
for same model
33
Purchase Task
Display
Product
Detail
Add To
Display
Cart
Cart
Checkout
Buy
New Computer
Continue
Shopping
Retrieve
Profile
Confirm
Address
&
Payment
Confirm
Confirm
Order
34
Submit
Order
Continue
Shopping
Purchase Task
Controller
Display
Product
Detail
Add To
Display
Cart
Cart
“Continu
e
Shopping”
“Checkout”
Navigate
Retrieve
Profile
Views
Buy
Computer
Confirm
Address
&
Payment
Submit
Order
State
“Confirm”
UI Navigation
State
Single User
UI Process
Confirm
Order
“Continu
e
Shopping”
Graph
35
Reference
Data
Model
Purchase Task
Controller
Display
Product
Detail
Add To
Display
Cart
Cart
“Continu
e
Shopping”
“Checkout”
Buy
Computer
Navigate
Retrieve
Profile
Views
Submit
Order
Confirm
Address
&
Payment
State
“Confirm”
UI Navigation
State
Single User
UI Process
Confirm
Order
“Continu
e
Shopping”
Flow/Graph
36
Reference
Data
Model
Event Delegation Model
• The Delegation Event Model (事件委派模式)
– Model used by Java to handle user interaction with
GUI components
– Describes how your program can respond to user
interaction
• Three important components:
– Event Source
– Event
– Event Listener/Handler
37
Event Source
• GUI component that generates the event
– Example: button, mouse, keyboard, etc
38
Event Listener/Handler
• Receives news of events and processes user's
interaction
– Example: displaying an information useful to the user,
computing for a value
39
Event Object
• Created when an event occurs (i.e., user interacts
with GUI component)
– ActionEvent => clicking button in GUI
– WindowEvent => closing a window
• Contains all necessary information about the event
that has occurred
– Type of event that has occurred
– Source of the event
– May have one of several event classes as data type
40
The Delegation Event Model
• A listener should be registered with a source
• Once registered, listener waits until an event occurs
• When an event occurs
– An event object created
– Event object is fired by the source to the registered listeners
• Once the listener receives an event object from the source
– Deciphers the notification
– Processes the event that occurred.
41
The Delegation Event Model
42
Registration of Listeners
• Event source registering a listener:
void add<Type>Listener(<Type>Listener listenerObj)
where,
– <Type> depends on the type of event source
• Can be Key, Mouse, Focus, Component, Action and others
– One event source can register several listeners
• Registered listener being unregistered:
void remove<Type>Listener(<Type>Listener listenerObj)
43
Design Pattern Used in Java Event Handling
• Observer Pattern
– Aliases :Dependents, Publish-Subscribe
– Category: behavioral
• General Purpose
– When one object changes state, all the dependent objects are
notified and updated.
– Allows for consistency between related objects without tightly
coupling classes
• e.g. “reduces coupling between objects”
• “publish and subscription” services
• eBay
44
Observer Pattern - Key Players
• Subject
– Knows its observers – provides interface for attaching/detaching
subjects
• Observer
– Defines an interface for notifying the subjects of changes to the
object (ex. Data)
• ConcreteSubject
– Sends notification to observers when state changes by storing
state to ConcreteObserver object
• ConcreteObserver
– Implements Observer interface to keep state consistent with
subject
45
Observer UML
46
Real-World Example
“General Broadcast”
Observers “tuning in” to the notification
47
Data Example
Subject
Interface
Browser
PDA
Cell Phone
Terminal
XML
xyz…
Data is sent to the various observers
Web
Browser
Cell
Phone
PDA
Observers
48
Terminal
Weather Monitor Application
49
Weather Monitor Application
50
Weather Monitor Application
public interface Subject {
public void registerObserver( Observer o );
public void removeObserver( Observer o );
public void notifyObservers();
}
public interface Observer {
public void update( Subject o );
}
public interface DisplayElement {
public void display( );
}
51
Weather Monitor Application
52
Weather Monitor Application
53
Weather Monitor Application
54
Weather Monitor Application
55
java.util Class Observable
• Java Built-in Observer
56
Observer Pattern: Interaction
57
Event-Listener-Model
• Provide (part of) the information in event objects passed
to the update() method.
• Example:
58
Event Model
Every event handler requires three pieces of code:
• In event handler class, one line of code specifies that the class
either implements a listener interface or extends a class that
implements a listener interface. For example:
public class MyClass implements ActionListener {
• Registers an instance of the event handler class as a listener
on one or more components. For example:
someComponent.addActionListener(instanceOfMyClass);
• The event handler class implements the methods in the
listener interface. For example:
public void actionPerformed(ActionEvent e) {
...//code that reacts to the action... }
59
Naming Convention
• For event XYZ …
–
–
–
–
Event class: XYZEvent
Listener interface: XYZListener
Adapter class: XYZAdapter
Registration method: addXYZListener()
60
Event Class
• Java provides two super classes to define event class:
– java.util.EventObject (for non-GUI events)
– java.awt.AWTEvent (typically for GUI controls)
• EventObject has at least one method getSource that returns an
Object at which the event occurred.
• For your custom event class you extend this class and add other
methods needed.
• Events can be divided into two groups:
– low-level events (底层事件类)
– semantic events(语义事件类)
61
Low-level Events
• Low-level events represent window-system occurrences or lowlevel input.
– ComponentEvent(组件事件) : A component moved, changed size, or
changed visibility (also, the root class for the other component-level events).
– ContainerEvent(容器事件): A container's contents changed because a
component was added or removed.
– WindowEvent(窗口事件): Window has changed its status
– FocusEvent(焦点事件): A Component has gained or lost the input focus.
– KeyEvent(键盘事件): A key is pressed, released
– MouseEvent(鼠标事件): A mouse button is pressed, released, clicked
– Mouse Motion Events (鼠标移动事件): A mouse is moved or dragged
62
Semantic Events
• Whenever possible, you should listen for semantic events rather
than low-level events.
– make code robust and portable
– ActionEvent(动作事件): User clicks a button, presses Enter while typing in a
text field, or chooses a menu item
– AdjustmentEvent(调节事件): Emitted by Adjustable objects such as scrollbar
– ItemEvent(项目事件): An item was selected or deselected for a List
– TextEvent(文本事件): An object's text changed
63
Event Classes
java.lang.Object
java.util.EventObject
ActionEvent
ContainerEvent
AdjustmentEvent
FocusEvent
ItemEvent
PaintEvent
ComponentEvent
WindowEvent
java.awt.AWTEvent
InputEvent
Key
Class name
Interface name
KeyEvent
64
MouseEvent
Event Classes
65
Event-listener Interfaces
66
Event Listeners
• Classes that implement the <Type>Listener interfaces
• An event listener is used to handle the corresponding
event.
• All event listener methods take an event as an argument
• For example:
public interface KeyListener extends EventListener {
public void keyPressed(KeyEvent ev);
public void keyReleased(KeyEvent ev);
public void keyTyped(KeyEvent ev);
}
67
Example
import java.awt.event.*;
import javax.swing.*;
public class TestButton {
public static void main(String args[]) {
JFrame f = new JFrame("Test");
JButton b = new JButton("Press Me!"); // create a button
// register an action listener
b.addActionListener(new ButtonActionListener());
f.setLayout(new FlowLayout());
f.add(b);
f.setSize(200,100);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}}
// Action listener class
class ButtonActionListener implements ActionListener {
public void actionPerformed(ActionEvent e){
System.out.println(" Button pressed! ");
}}
68
Register and Remove Listener
• Register Listener
– public void add<ListenerType>
(<ListenerType>listener);
• Remove Listener
– public void remove<ListenerType>
(<ListenerType>listener);
69
Register and Remove Listener
• For Example:
public class Button extends Component {
……
public synchronized void
addActionListener(ActionListener l);
public synchronized void
removeActionListener(ActionListener l);
……
}
70
AWT Event and its Listener Interface
• ActionEvent
– 激活组件
– ActionListener
– actionPerformed(ActionEvent)
71
AWT Event and its Listener Interface
• ItemEvent
– 选择了某些项目
– ItemListener
– itemStateChanged(ItemEvent)
72
AWT Event and its Listener Interface
• MouseEvent
–
–
–
–
鼠标移动
MouseMotionListener
mouseDragged(MouseEvent)
mouseMoved(MouseEvent)
73
AWT Event and its Listener Interface
• MouseEvent
–
–
–
–
–
–
–
鼠标点击等
MouseListener
mousePressed(MouseEvent)
mouseReleased(MouseEvent)
mouseEntered(MouseEvent)
mouseExited(MouseEvent)
mouseClicked(MouseEvent)
74
AWT Event and its Listener Interface
• KeyEvent
–
–
–
–
–
键盘输入
KeyListener
keyPressed(KeyEvent)
keyReleased(KeyEvent)
keyTyped(KeyEvent)
75
AWT Event and its Listener Interface
• FocusEvent
–
–
–
–
组件收到或失去焦点
FocusListener
focusGained(FocusEvent)
focusLost(FocusEvent)
76
AWT Event and its Listener Interface
• AdjustmentEvent
– 移动了滚动条等组件
– AdjustmentListener
– adjustmentValueChanged(AdjustmentEvent)
77
AWT Event and its Listener Interface
• ComponentEvent
–
–
–
–
–
–
对象移动缩放显示隐藏等
ComponentListener
componentMoved(ComponentEvent)
componentHidden(ComponentEvent)
componentResized(ComponentEvent)
componentShown(ComponentEvent)
78
AWT Event and its Listener Interface
• WindowEvent
–
–
–
–
–
–
–
–
–
窗口收到窗口级事件
WindowListener
windowClosing(WindowEvent)
windowOpened(WindowEvent)
windowIconified(WindowEvent)
windowDeiconified(WindowEvent)
windowClosed(WindowEvent)
windowActivated(WindowEvent)
windowDeactivated(WindowEvent)
79
AWT Event and its Listener Interface
• ContainerEvent
–
–
–
–
容器中增加删除了组件
ContainerListener
componentAdded(ContainerEvent)
componentRemoved(ContainerEvent)
80
AWT Event and its Listener Interface
• TextEvent
– 文本字段或文本区发生改变
– TextListener
– textValueChanged(TextEvent)
81
import java.awt.*;
import java.awt.event.*;
public class ThreeListener implements
MouseMotionListener,MouseListener,WindowListener {
private Frame f;
private TextField tf;
public static void main(String args[]) {
ThreeListener two = new ThreeListener();
two.go();
}
public void go() {
f = new Frame("Three listeners example");
f.add(new Label("Click and drag the mouse"),"North");
tf = new TextField(30);
f.add(tf,"South"); //使用缺省的布局管理器
f.addMouseMotionListener(this);
f.addMouseListener(this);
f.addWindowListener(this);
f.setSize(300,200);
f.setVisible(true);
Example-Implement a listener interface
82
public void mouseDragged (MouseEvent e) {
Example(Cont.)
String s = "Mouse dragging : X="+e.getX()+"Y = "+e.getY();
tf.setText(s);
}
public void mouseMoved(MouseEvent e){}
public void mouseClicked(MouseEvent e){}
public void mouseEntered(MouseEvent e){
String s = "The mouse entered";
tf.setText(s);
}
public void mouseExited(MouseEvent e){
String s = "The mouse has left the building";
tf.setText(s);
}
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent 83
e){}
Example(Cont.)
public void windowClosing(WindowEvent e) {
System.exit(1);
}
public void windowOpened(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowActivated(WindowEvent e) { }
public void windowDeactivated(WindowEvent e) {}
}
84
Example(Cont.)
• 可以声明多个接口,接口之间用逗号隔开。
– ……implements MouseMotionListener, MouseListener,
WindowListener
• 可以由同一个对象监听一个事件源上发生的多种事件,则对象f 上发生的多
个事件都将被同一个监听器接收和处理。 :
f.addMouseMotionListener(this);
f.addMouseListener(this);
f.addWindowListener(this);
• 事件处理者和事件源处在同一个类中。本例中事件源是Frame f,事件处理
者是类ThreeListener,其中事件源Frame f是类ThreeListener的成员变量。
• 可以通过事件对象获得详细资料,比如本例中就通过事件对象获得了鼠标
发生时的坐标值。
public void mouseDragged(MouseEvent e) {
String s="Mouse dragging :X="+e.getX()+"Y="+e.getY();
tf.setText(s);
}
85
Event Adapter Classes
• An alternate technique for creating listener classes
– Event Adapter
• Built-in in Java
• Why use Adapter classes?
– Implementing all methods of an interface takes a lot of
work
– Interested in implementing some methods of the
interface only
86
Event Adapter Classes
• Each adapter class implements the corresponding listener
and provides empty method definitions
• When you derive a listener class from an adapter class,
you only need to override the event methods that pertain
to the program
• Empty definitions for unused event methods do not need
to be defined because they are provided via inheritance
87
Mouse Adapter
import java.awt.*;
import java.awt.event.*;
public class MouseClickHandler extends
MouseAdaper{
public void mouseClicked(MouseEvent e) {
……
}
}
88
Event Adapters
• Event adapters in the package java.awt.event:
–
–
–
–
–
–
–
ComponentAdapter( 组件适配器)
ContainerAdapter( 容器适配器)
FocusAdapter( 焦点适配器)
KeyAdapter( 键盘适配器)
MouseAdapter( 鼠标适配器)
MouseMotionAdapter( 鼠标运动适配器)
WindowAdapter( 窗口适配器)
89
Example: Resizing Component
• To prevent windows from being resized too small, use
ComponentEvent and ComponentApdater
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class WinJava extends JFrame {
public static void main(String args[]) {
JFrame f = new WinJava("Win Java");
f.setSize(500,500);
f.setVisible(true);
}
public WinJava(String name){
super(name);
setResizable(true);
addComponentListener(new WinJavaComponentListener(400,300));
}
}
90
Example (Cont.)
class WinJavaComponentListener extends ComponentAdapter {
private int width, height;
public void componentResized(ComponentEvent e) {
Component c = e.getComponent();
if (c.getWidth() < width || c.getHeight() < height) {
c.setSize(Math.max(width, c.getWidth()),
Math.max(height, c.getHeight()));
}
}
public WinJavaComponentListener(int w, int h) {
width = w; height = h;
}
}
91
Event Handling
• Options for implementing listeners:
– listener class (implement interface or extend adapter)
– named inner classes
– anonymous inner classes
92
Inner Classes
• Class declared within another class
• Why use inner classes?
– Help simplify your programs
– Especially in event handling
93
Example-inner class
import java.awt.* ;
import java.awt.event.*;
public class InnerClass{
private Frame f;
private TextField tf;
public InnerClass() {
f = new Frame("Inner classes example");
tf = new TextField(30);
}
public static void main(String args[]) {
InnerClass obj = new InnerClass();
obj.launchFrame();
}
94
Inner class
public void launchFrame() {
Label label = new Label("Click and drag the mouse");
f.add(label,BorderLayout.NORTH);
f.add(tf,BorderLayout.SOUTH);
f.addMouseMotionListener(new MyMouseMotionListener());
f.setSize(300,200);
f.setVisible(true);
}
class MyMouseMotionListener extends MouseMotionAdapter {
public void mouseDragged(MouseEvent e) {
String s="Mouse dragging: x="+e.getX()+"Y="+e.getY();
tf.setText(s);
}
}
}
95
Anonymous Inner Class
import java.awt.* ;
import java.awt.event.*;
public class AnonymousClass{
private Frame f;
private TextField tf;
public AnonymousClass(){
f=new Frame("Inner classes example");
tf=new TextField(30);
}
public static void main(String args[]) {
AnonymousClass obj=new AnonymousClass();
obj.launchFrame();
}
96
Anonymous Inner Class
public void launchFrame() {
Label label=new Label("Click and drag the mouse");
f.add(label,BorderLayout.NORTH);
f.add(tf,BorderLayout.SOUTH);
f.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e){
String s="Mouse dragging: x = " + e.getX() +
"Y=" + e.getY();
tf.setText(s);
}
});
f.setSize(300,200);
f.setVisible(true);
}
}
97
Lab
•
•
•
•
Create a calculater using Java GUI
Unit 3.2.2
Unit 3.2.3
Exercise 8(new)
98