0% found this document useful (0 votes)
3 views

Module-5

The document provides an overview of the Event Model in Java, which consists of events, event sources, and event listeners. It explains the Delegation Event Model, the use of adapter classes to simplify event handling, and the role of inner classes in managing events. Additionally, it covers GUI components, layout managers, and the principles of event-driven programming in Java applications.

Uploaded by

moher64238
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Module-5

The document provides an overview of the Event Model in Java, which consists of events, event sources, and event listeners. It explains the Delegation Event Model, the use of adapter classes to simplify event handling, and the role of inner classes in managing events. Additionally, it covers GUI components, layout managers, and the principles of event-driven programming in Java applications.

Uploaded by

moher64238
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 50

Module - 5

Event Model

Event Model is based on the following three components:


• Events
• Events Sources
• Events Listeners
Events

• The Events are the objects that define state change in a


source. An event can be generated as a reaction of a
user while interacting with GUI elements. Some of the
event generation activities are moving the mouse
pointer, clicking on a button, pressing the keyboard key,
selecting an item from the list, and so on. We can also
consider many other user operations as events.
• The Events may also occur that may be not related to
user interaction, such as a timer expires, counter
exceeded, system failures, or a task is completed, etc.
We can define events for any of the applied actions.
Event Sources
• A source is an object that causes and generates an event. It
generates an event when the internal state of the object is
changed. The sources are allowed to generate several different
types of events.
• A source must register a listener to receive notifications for a
specific event. Each event contains its registration method. Below
is an example:
• public void addTypeListener (TypeListener e1)
• From the above syntax, the Type is the name of the event, and e1
is a reference to the event listener. For example, for a keyboard
event listener, the method will be called as addKeyListener().
For the mouse event listener, the method will be called
as addMouseMotionListener().
Event Listeners
• An event listener is an object that is invoked when an event
triggers. The listeners require two things; first, it must be
registered with a source; however, it can be registered with
several resources to receive notification about the events.
Second, it must implement the methods to receive and
process the received notifications.
• The methods that deal with the events are defined in a set of
interfaces. These interfaces can be found in the java.awt.event
package.
• For example, the MouseMotionListener interface provides
two methods when the mouse is dragged and moved. Any
object can receive and process these events if it implements
the MouseMotionListener interface.
Types of Events
Foreground Events:
• The foreground events are those events that require direct
interaction of the user. These types of events are generated as a
result of user interaction with the GUI component. For example,
clicking on a button, mouse movement, pressing a keyboard key,
selecting an option from the list, etc.
Background Events :
• The Background events are those events that result from the
interaction of the end-user. For example, an Operating system
interrupts system failure (Hardware or Software).
• To handle these events, we need an event handling mechanism
that provides control over the events and responses.
Delegation Event Model
• The Delegation Model is available in Java since Java 1.1. it provides a new
delegation-based event model using AWT to resolve the event problems. It
provides a convenient mechanism to support complex Java programs.
Design Goals
• It is easy to learn and implement
• It supports a clean separation between application and GUI code.
• It provides robust event handling program code which is less error-prone
(strong compile-time checking)
• It is Flexible, can enable different types of application models for event flow
and propagation.
• It enables run-time discovery of both the component-generated events as
well as observable events.
• It provides support for the backward binary compatibility with the previous
model.
Adapter Classes

• Java adapter classes provide the default implementation of


listener interfaces. If you inherit the adapter class, you will
not be forced to provide the implementation of all the
methods of listener interfaces. So it saves code.
• The adapter classes are found in java.awt.event,
java.awt.dnd and javax.swing.event packages. The
Adapter classes with their corresponding listener interfaces
are given below.
java.awt.event Adapter classes
java.awt.dnd Adapter classes
javax.swing.event Adapter classes
Need for Adapter Classes

• To comprehend the role of adapter classes, one must first understand the
concept of event listeners in Java. An event listener is an interface that contains
methods invoked when certain events occur.
• For instance, the WindowListener interface has seven different methods
corresponding to various window events, like window opening, closing,
deiconifying, etc. If a class implements this interface, it's required to provide
implementations for all seven methods, even if it's only interested in one event.
• This is where adapter classes come in handy. Since they provide default (empty)
implementations for all event handling methods, you can create a subclass from
an adapter class, and override only those methods you're interested in.
Java WindowAdapter
Java MouseAdapter
Java MouseMotionAdapter
Benefits of Java Adapter Class
Inner Classes
• Recall that an inner class is a class defined within another class, or even within an
expression. This section illustrates how inner classes can be used to simplify the code
when using event adapter classes.
• To understand the benefit provided by inner classes, consider the applet shown in the
following listing. It does not use an inner class. Its goal is to display the string "Mouse
Pressed" in the status bar of the applet viewer or browser when the mouse is pressed.
• There are two top-level classes in this program. MousePressedDemo extends Applet,
and MyMouseAdapter extends MouseAdapter.
• The init( ) method of MousePressedDemo instantiates MyMouseAdapter and provides
this object as an argument to the addMouseListener( ) method. Notice that a reference to
the applet is supplied as an argument to the MyMouseAdapter constructor. This
reference is stored in an instance variable for later use by the mousePressed( ) method.
When the mouse is pressed, it invokes the showStatus( ) method of the applet
Event-driven Programming and
Graphical User Interfaces
(GUIs) with Swing/AWT
Why learn GUIs?
• Learn about event-driven programming techniques
• Practice learning and using a large, complex API
• A chance to see how it is designed and learn from it:
• model-view separation
• design patterns
• refactoring vs. reimplementing an ailing API
• Because GUIs are neat!

• Caution: There is way more here than you can


memorize.
• Part of learning a large API is "letting go."
• You won't memorize it all; you will look things up as you need
them.
• But you can learn the fundamental concepts and general
ideas.
Java GUI History
• Abstract Windowing Toolkit (AWT): Sun's initial
effort to create a set of cross-platform GUI classes.
(JDK 1.0 - 1.1)
• Maps general Java code to each operating system's real GUI
system.
• Problems: Limited to lowest common denominator; clunky
to use.

• Swing: A newer GUI library written from the ground


up that allows much more powerful graphics and GUI
construction. (JDK 1.2+)
• Paints GUI controls itself pixel-by-pixel rather than handing
off to OS.
• Benefits: Features; compatibility; OO design.

• Problem: Both exist in Java now; easy to get them


GUI terminology
• window: A first-class citizen of the graphical
desktop.
• Also called a top-level container.
• examples: frame, dialog box, applet

• component: A GUI widget that resides in a


window.
• Also called controls in many other languages.
• examples: button, text box, label

• container: A logical grouping for storing


components.
• examples: panel, box
Components
Swing inheritance hierarchy
• Component (AWT) import java.awt.*;
• Window import javax.swing.*;
• Frame
• JFrame (Swing)
• JDialog

• Container
• JComponent (Swing)
• JButton JColorChooser JFileChooser
• JComboBox JLabel JList
• JMenuBar JOptionPane JPanel
• JPopupMenu JProgressBar JScrollbar
• JScrollPane JSlider JSpinner
• JSplitPane JTabbedPane JTable
• JToolbar JTree JTextArea
• JTextField ...
Component properties
• Each has a get (or is) accessor and a set modifier
method.
• examples:
name getColor,
type setFont, setEnabled,
description
isVisible
background Color background color behind component
border Border border line around component
enabled boolean whether it can be interacted with
focusable boolean whether key text can be typed on it
font Font font used for text in component
foreground Color foreground color of component
height, width int component's current size in pixels
visible boolean whether component can be seen
tooltip text String text shown when hovering mouse
size, minimum / Dimension various sizes, size limits, or desired
maximum / preferred size sizes that the component may take
JFrame
a graphical window to hold other components

• public JFrame()
public JFrame(String title)
Creates a frame with an optional title.

• Call setVisible(true) to make a frame appear on


the screen after creating it.

• public void add(Component comp)


Places the given component or container inside
the frame.
More JFrame

• public void setDefaultCloseOperation(int op)


Makes the frame perform the given action when it
closes.
• Common value passed: JFrame.EXIT_ON_CLOSE
• If not set, the program will never exit even if the frame is
closed.

• public void setSize(int width, int height)


Gives the frame a fixed size in pixels.

• public void pack()


Resizes the frame to fit the components inside it
snugly.
JButton
a clickable region for causing actions to occur

• public JButton(String text)


Creates a new button with the given string as its
text.

• public String getText()


Returns the text showing on the button.

• public void setText(String text)


Sets button's text to be the given string.
GUI example
import java.awt.*; // Where is the other button?
import javax.swing.*;

public class GuiExample1 {


public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(300, 100));
frame.setTitle("A frame");

JButton button1 = new JButton();


button1.setText("I'm a button.");
button1.setBackground(Color.BLUE);
frame.add(button1);

JButton button2 = new JButton();


button2.setText("Click me!");
button2.setBackground(Color.RED);
frame.add(button2);

frame.setVisible(true);
}
Sizing and positioning
How does the programmer specify where each
component appears, how big each component should
be, and what the component should do if the window is
resized / moved / maximized / etc.?

• Absolute positioning (C++, C#, others):


Programmer specifies exact pixel coordinates of every
component.
• "Put this button at (x=15, y=75) and make it 70x31 px in
size."

• Layout managers (Java):


Objects that decide where to position each component
based on some general rules or criteria.
• "Put these four buttons into a 2x2 grid and put these text
Containers and layout
• Place components in a container; add the
container to a frame.
• container: An object that stores components and
governs their positions, sizes, and resizing behavior.
JFrame as container
A JFrame is a container. Containers have these
methods:

• public void add(Component comp)


public void add(Component comp, Object info)
Adds a component to the container, possibly giving
extra information about where to place it.

• public void remove(Component comp)

• public void setLayout(LayoutManager mgr)


Uses the given layout manager to position components.

• public void validate()


Refreshes the layout (if it changes after the container is
onscreen).
Preferred sizes
• Swing component objects each have a certain
size they would "like" to be: Just large enough to
fit their contents (text, icons, etc.).
• This is called the preferred size of the component.

• Some types of layout managers (e.g. FlowLayout)


choose to size the components inside them to the
preferred size.
• Others (e.g. BorderLayout, GridLayout) disregard
the preferred size and use some other scheme to size
the components.

Buttons at preferred size:Not preferred size:


FlowLayout
public FlowLayout()

• treats container as a left-to-right, top-to-bottom


"paragraph".
• Components are given preferred size, horizontally and
vertically.
• Components are positioned in the order added.
• If too long, components wrap around to the next line.

myFrame.setLayout(new FlowLayout());
myFrame.add(new JButton("Button 1"));

• The default layout for containers other than JFrame (seen


BorderLayout
public BorderLayout()

• Divides container into five regions:


• NORTH and SOUTH regions expand to fill region
horizontally,
and use the component's preferred size vertically.
• WEST and EAST regions expand to fill region vertically,
and use the component's preferred size horizontally.
• CENTER uses all space not occupied by others.
myFrame.setLayout(new BorderLayout());
myFrame.add(new JButton("Button 1"), BorderLayout.NORTH);

• This is the default layout for a JFrame.


GridLayout
public GridLayout(int rows, int columns)

• Treats container as a grid of equally-sized rows


and columns.
• Components are given equal horizontal / vertical
size, disregarding preferred size.
• Can specify 0 rows or columns to indicate
expansion in that direction as needed.
Event Listeners
Graphical events
• event: An object that represents a user's
interaction with a GUI component; can be
"handled" to create interactive components.

• listener: An object that waits for events and


responds to them.
• To handle an event, attach a listener to a component.
• The listener will be notified when the event occurs
(e.g. button click).
Event-driven programming
• event-driven programming: A style of coding
where a program's overall flow of execution is
dictated by events.
• Rather than a central "main" method that drives
execution,
the program loads and waits for user input events.
• As each event occurs, the program runs particular
code to respond.
• The overall flow of what code is executed is
determined by the series of events that occur, not a
pre-determined order.
Event hierarchy
import java.awt.event.*;

• EventListener
EventObject
• (AWT)
AWTEventListener
AWTEvent
• • ActionEvent
ActionListener
• • TextEvent
TextListener
• • ComponentEvent
ComponentListener
• • FocusEvent
FocusListener
• • WindowEvent
WindowListener
• InputEvent
• KeyEvent
• KeyListener
• MouseEvent
• MouseListener
Action events
• action event: An action that has occurred on a
GUI component.
• The most common, general event type in Swing.
Caused by:
• button or menu clicks,
• check box checking / unchecking,
• pressing Enter in a text field, ...

• Represented by a class named ActionEvent


• Handled by objects that implement interface
ActionListener
Implementing a listener
public class name implements ActionListener {
public void actionPerformed(ActionEvent event) {
code to handle the event;
}
}

• JButton and other graphical components have


this method:
• public void addActionListener(ActionListener al)
Attaches the given listener to be notified of clicks and
events that occur on this component.
Nested classes
• nested class: A class defined inside of another
class.

• Usefulness:
• Nested classes are hidden from other classes
(encapsulated).
• Nested objects can access/modify the fields of their
outer object.

• Event listeners are often defined as nested


classes inside a GUI.
Nested class syntax
// enclosing outer class
public class name {
...

// nested inner class


private class name {
...
}
}

• Only the outer class can see the nested class or make
objects of it.
• Each nested object is associated with the outer object that
created it, so it can access/modify that outer object's
methods/fields.
Static inner classes
// enclosing outer class
public class name {
...

// non-nested static inner class


public static class name {
...
}
}

• Static inner classes are not associated with a particular


outer object.
• They cannot see the fields of the enclosing class.
• Usefulness: Clients can refer to and instantiate static inner
classes:
GUI event example
public class MyGUI {
private JFrame frame;
private JButton stutter;
private JTextField textfield;

public MyGUI() {
...
stutter.addActionListener(new StutterListener());
}
...

// When button is clicked, doubles the field's text.


private class StutterListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
String text = textfield.getText();
textfield.setText(text + text);
}
}

You might also like