0% found this document useful (0 votes)
18 views80 pages

Chapter - 1 Final

chapter - 1

Uploaded by

Abraham dagne
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)
18 views80 pages

Chapter - 1 Final

chapter - 1

Uploaded by

Abraham dagne
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

Arba Minch University

Jun 23, 2024


Institute of Technology
Faculty of Computing & Software Engineering

Advanced

Advanced Programming
Programming
(SENG2083)
Mr. Addisu M. (Asst. Prof) G3 SE - Regular
1
Chapter 1

AWT and Swing


2

Advanced Programming Jun 23, 2024


Outline

Jun 23, 2024


 Introduction to GUI
 Introduction to AWT
 Introduction to Swing
 Introduction to Component, Container,

Advanced Programming
Panels, Window, Frame
 Implementation of JFrame and Adding
Component
 Event Handling
3
Jun 23, 2024
Introduction to GUI (Graphical User Interface)
 GUI (Graphical User Interface) – visual interface to program
 built from GUI components (buttons, scrollbars, menus, labels,
text fields, etc)
 GUI component – an object with which the user interacts via
mouse or keyboard
 gives an application a distinctive “look and feel”

Advanced Programming
 appearance and how user interacts with the program are know
as the program “look and feel”
 Classes that are used to create GUI components are part of
java.awt or javax.swing package
 Both these packages provide rich set of user interface components
4
GUI vs Non-GUI

Jun 23, 2024


 Classes present in AWT and Swing packages can be
classified into two broad categories
 GUI classes – visible and user can interact with them
 Example: Jbutton, JFrame & JRadioButton, etc

Advanced Programming
 Non-GUI support classes – provide services and
perform necessary functions for GUI classes
 do not produce any visual output
 Example: Layout managers & Event handling
5
GUI Components

Jun 23, 2024


 two main sets of visual components and containers for user
interface design in JAVA:
 AWT (Abstract Window Toolkit) and Swing
AWT Swing
Fine for developing comprehensive GUI
Fine for developing simple GUI
projects
Prone to platform-specific bugs More robust, versatile, and flexible

Advanced Programming
Called Heavyweight components called lightweight components
Swing GUI component classes are
Prefix J is not used here
named with a prefixed J
E.g.: Button, Label, TextField E.g.: JButton, JLabel, JTextField

 AWT components are still supported in Java, it is better to learn to how


program using Swing components, because AWT UI components will
eventually fade away. 6
What is AWT?

Jun 23, 2024


 AWT (Abstract Windowing Toolkit)
 an API designed to provide a common set of tools for GUI
or window-based application design/development that work
on a variety of platforms
 Event-driven: window is displayed, and when things

Advanced Programming
happen, an event handler is called
 GUI is built of graphical elements called components, such
as buttons, scrollbars, and text fields, labels etc

7
What is AWT?

Jun 23, 2024


 AWT (Abstract Windowing Toolkit)
 Components allow the user to interact with program and provide
the user with visual feedback about state of the program
 Must import java.awt.* and java.awt.event.*
 General Layout of AWT components are platform-dependent

Advanced Programming
i.e. components are displayed according to the view of OS
 its components are often called Heavy Weight Components
(HWC) as they rely on local platform’s OS
 its components are using resources of underlying OS

8
What is AWT?

Jun 23, 2024


 java.awt package provides classes for AWT API such as
TextField, Lael, TextArea, RadioButton, CheckBox, Choice,
List, etc.
 To develop the GUI to use AWT

Advanced Programming
 set of classes and Interfaces which are required to develop GUI
components together are called as ‘Toolkit’.
 GUI components will be used to design GUI programs
 Writing a program to display the created GUI components on the
windows is called as ‘windowing’
9
Hierarchy of AWT & Swing Classes

Jun 23, 2024


Advanced Programming
10
Java GUI API

Jun 23, 2024


• GUI API contains classes that can be classified into
three groups:
 Container classes,

Advanced Programming
 Component classes, and

 Helper classes

11
Container Classes

Jun 23, 2024


• a specialized component that holds other components
like buttons, textfields, labels etc at their specific
locations
• Window, Panel, Applet, Frame, and Dialog are container
classes for AWT components

Advanced Programming
 Note:
 A container itself is a component, therefore we can add a
container inside container
• four types of containers :
1. Window 3. Frame
2. Panel 4. Dialog 12
Container Classes

Jun 23, 2024


• Window
 have no borders and menu bars
 Window class is rarely used directly
 You must use frame, dialog or another window for creating a
window

Advanced Programming
 Create an instance of Window class to create this container
 Constructor: public Window(Frame parent);
 Parent frame window is necessary because only objects of
the Frame class or it’s subclasses contain the functionality
needed to implement an independent application window
13
Container ClassesA

Jun 23, 2024


• Frame
 Rectangular resizable Box contain title bar & border and can have
menu bars
 Every frame by default will contain a title, minimize,
maximize and close Buttons
 By default the size of frame OXO (zero by zero) pixels

Advanced Programming
 can have other components like button, text field, etc
 Implements MenuContainer interface. Hence capable of working
with MenuBar objects
 Constructor:
public Frame() :-Creates an untitled frame window
public Frame(String title) :-String argument used as frame’s window
title 14
Container Classes

Jun 23, 2024


• Frame
 Commonly Used Method(s):
 setTitle(String title)
 setMenuBar(MenuBar mb)
 setIconImage(Image img)
 most widely used while developing an AWT application

Advanced Programming
 can be created in two ways:
 Create the object of Frame by Instantiating Frame class
 Ex: Frame f = new Frame();
 Create the object of any class that extends Frame class
(inheritance)
 Ex: class MyFrame extends Frame 15
Container Classes

Jun 23, 2024


• by Instantiating Frame class
import java.awt.*;
public class Testawt {
Testawt() {
Frame fm=new Frame(); //Creating a frame
Label lb = new Label("welcome to java graphics"); //Creating label
fm.add(lb);//adding label to the frame

Advanced Programming
fm.setSize(300, 300); //setting frame size.
fm.setVisible(true); //set frame visibilty true
}
public static void main(String args[]) {
Testawt ta = new Testawt();
}
}
16
Container Classes

Jun 23, 2024


• Create object of any class that extends Frame class
package testawt;
import java.awt.*;
import java.awt.event.*;
public class Testawt extends Frame {
public Testawt() {
Button btn = new Button("Hello World");
add(btn); //adding a new Button
setSize(400, 500); //setting size

Advanced Programming
setTitle("StudyTonight"); //setting title
setLayout(new FlowLayout());//set default layout
//arranging components in a line, one after another(in a flow)
setVisible(true); //set frame visibilty true
}
public static void main (String[] args) {
Testawt ta = new Testawt(); //creating a frame.
}
}
17
Container Classes

Jun 23, 2024


• Frame - Points to note:
 While creating a frame, the following two attributes are a must:
setSize(int width, int height);
setVisible(true);
 When you create other components like Buttons, TextFields, etc,
you need to add it to the frame by using
add(Component's Object);

Advanced Programming
 You can add the following method also for resizing the frame
setResizable(true);
• Panel
 doesn't contain title bar, border or menu bar
 generic container for holding components like button, text field etc
 An instance of Panel class creates a container, in which we can add
components 18
Container Classes

Jun 23, 2024


import java.awt.*;
Example
public class PanelExample {
PanelExample()
{
Frame f= new Frame("Panel Example");
Panel panel=new Panel();

Advanced Programming
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
Button b1=new Button("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
Button b2=new Button("Button 2");
b2.setBounds(100,100,80,30); 19
Container Classes

Jun 23, 2024


b2.setBackground(Color.green); Example
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);

Advanced Programming
}
public static void main(String args[])
{
new PanelExample();
}
} 20
Component Classes

Jun 23, 2024


• root class of all UI classes including container classes
• elements like button, text fields, scroll bars, etc. are
called components
• there are classes for each component
• An instance of Component can be displayed on

Advanced Programming
the screen
 Both Component & JComponent are abstract classes
• In order to place every component in a particular
position on a screen, we need to add them to a
container
21
Component Classes

Jun 23, 2024


 Button:
 used to perform some operation when the user clicks on a
button.
 Creation of button:

Advanced Programming
Button b = new Button(String label);
b = new Button(“OK”); //create the components
b.setBounds(100,100,80,40); //(x, y, w, h) set boundaries
this.add(b); //adding the component to the frame
22
Component Classes

Jun 23, 2024


 Label :
 used to display a message on the frame
 generally used along with other components.
 Creation of Label: Label l = new Label(String);
 TextField:

Advanced Programming
 allow the user to enter some text.
 Creation of TextField: TextField tf = new TextField(size);
 Checkbox:
 allows to select any # of options from group of options
 Creation of checkbox: Checkbox cb = new Checkbox();
23
Component Classes

Jun 23, 2024


 RadioButton: allow to select any one option from group of
options
 special kind of checkbox that is used to select only one option
 No button class is available in java.awt package
 When we add checkbox to a checkbox group, they become radio
button automatically.
 To place the options under single group we are support to use

Advanced Programming
class called “CheckboxGroup”
 Creation of RadioButton:
CheckboxGroup cbg = new CheckboxGroup();
Checkbox rb = new Checkbox(Label, cbg, boolean);
mal = new Checkbox (“Male", cbg, true);
femal = new Checkbox (“Female", cbg, false);
add (mal); add (femal); 24
Helper Classes

Jun 23, 2024


• used to support GUI Components
• They are used to describe the properties of GUI
components, such as graphics context, colors, fonts,
and dimension
• Example: Graphics, color, Font, FontMetrics,

Advanced Programming
Dimension, and LayoutManager
• not sub-classes of Component
• used to describe the properties of GUI components
25
What is Swing?

Jun 23, 2024


 set of classes that provides more powerful and flexible GUI than
AWT
 use to develop a better efficient & newest GUI components
 Swing components
 written, manipulated and displayed completely in java
 therefore also called pure java components

Advanced Programming
 called as light weight components which improve performance
of the application because amount of resources required is very
minimum
 Not depend on OS – manipulated & displayed completely in Java
 allow programmer to specify a uniform look and feel across all
platforms - appearance and how user interacts with program
 Consistent appearance for the components in different platform 26
Container classes

Jun 23, 2024


• base class for all AWT and Swing containers
• Top containers: JWindow, JFrame, JDialog, and JApplet
• JWindow appears anywhere on the desktop but does
not have decorations
 Usually used for splash screens that appears at the beginning

Advanced Programming
when running an application
• JDialog – resembles a small frame that pops up in front
of the application’s window
 used to communicate with user, by displaying certain messages
and waiting for user’s response via buttons
27
Container classes

Jun 23, 2024


• JFrame – a top-level window with title and border
 has decorations (close, iconify, minimize/maximize)
• JPanel – used to group certain related components
together over the main container of the application
 blank rectangular component that can contain other

Advanced Programming
components.
• ff code is used to populate a container with
components:
topLevelContainer.add(anyComponent)
28
Methods of Swing classes

Jun 23, 2024


• Commonly Used Method(s) from container class:
 void add(Component comp)
 void add(Component comp, Object constraints)
 void setLayout(LayoutManager mgr)
• Commonly Used Method(s) from component class:
 void setSize(intwidth, intheight)

Advanced Programming
 void setLocation(intx, inty)
 void setBounds(intx, inty, intw, inth)
 void setFont(Font f)
 void setBackground (Color c)
 void setVisible(boolean b) 29
Anatomy of an Application GUI

Jun 23, 2024


Internal structure
JFrame
JFrame

JPanel containers

JPanel
JButton

Advanced Programming
JButton JLabel
JLabel

30
Frame

Jun 23, 2024


 Commonly Used Constructor(s): JFrame() & JFrame(String title)
 Commonly Used Method(s):
setJMenuBar(JMenuBar mb)
setDefaultCloseOperation(int op)
getDefaultCloseOperation()
 default size is (0,0)

Advanced Programming
 have to set its size before using it
 default visibility status is false (i.e. not visible)
 have to set its visibility to true
 default layout manager is BorderLayout
 can change that if needed 31
Frame

Jun 23, 2024


 When closing JFrame, the frame is hidden but is still existing
and running (holding GUI resources)
 To close the frame and end the application either register a
window listener or specify a close behavior
 method setDefaultCloseOperation(intop) – used to specify
closing behavior of the JFrame, you may pass one of the ff static

Advanced Programming
variables as parameter:
 DISPOSE_ON_CLOSE: to close the current frame but doesn’t terminate
the application
 DO_NOTHING_ON_CLOSE: to ignore the closing operation
 EXIT_ON_CLOSE: to exit appln (close all frame & terminate appln)
 HIDE_ON_CLOSE: to just hide the frame (default behavior)
 The above variables are defined in interface WindowConstants 32
Frame

Jun 23, 2024


 Creating JFrame – 2 ways to create JFrame Window
1. by Instantiating JFrame class
import javax.swing.*; //importing swing package
import java.awt.*; //importing awt package
public class First {
JFrame jf;

Advanced Programming
public First() {
jf = new JFrame("MyWindow");//Creating with title
JButton btn = new JButton("Say Hello");//Creating Button
jf.add(btn); //adding button to frame
jf.setLayout(new FlowLayout());//setting layout
33
Frame

Jun 23, 2024


 Creating JFrame – 2 ways to create JFrame Window
1. by Instantiating JFrame class
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//
setting close operation
jf.setSize(400, 400); //setting size
jf.setVisible(true);//setting visibility

Advanced Programming
}
public static void main(String[] args) {
new First();
}
}
34
Frame

Jun 23, 2024


 Creating JFrame – 2 ways to create JFrame Window
2. by extending JFrame class
import javax.swing.*; //importing swing package
import java.awt.*; //importing awt package
public class Second extends JFrame {

Advanced Programming
public Second() {
setTitle("MyWindow"); //setting title of frame
JLabel lb = new JLabel("Welcome to My Second Window");
//Creating a label named Welcome to My Second Window
add(lb); //adding label to frame.
setLayout(new FlowLayout()); //setting layout using FlowLayout
object 35
Frame

Jun 23, 2024


 Creating JFrame – 2 ways to create JFrame Window
2. by extending JFrame class
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //setting
close operation.
setSize(400, 400);//setting size
setVisible(true);//setting visibility

Advanced Programming
}
public static void main(String[] args) {
new Second();
}
}
36
Frame

Jun 23, 2024


 Creating JFrame – 2 ways to create JFrame Window
 Points to note:
 Import javax.swing and java.awt package to use the classes
and methods of Swing
 While creating a frame, the following two attributes are a must
for visibility of the frame:

Advanced Programming
setSize(int width, int height);
setVisible(true);
 When you create components like Buttons, TextFields, etc, you
need to add it to the frame by using the method
add(Component's Object);
 You can add the following method also for resizing frame
37
setResizable(true);
Dialog

Jun 23, 2024


 Dialog class – used to create a top-level container Dialog
window which contains a set of components
 main function of a dialog box is to retrieve some input from
the user
 input can be an acknowledgment that they have read a

Advanced Programming
message or something they enter into a text area
 a perfect tool for collecting or displaying important
information
• Java provides several classes to create dialog boxes
 classes include JOptionPane, JDialog, and JFrame
39
Dialog

Jun 23, 2024


• JOptionPane Class
 You can create using one of several static methods belonging to the
JOptionPane class, include:
• showMessageDialog() – relays a message to the user
• showConfirmDialog() – asks question that requires confirmation
• showInputDialog() – prompts a user for input

Advanced Programming
 It provides standard dialog boxes, it has many options allowing you
to tweak its behavior
• INFORMATION_MESSAGE - default
• ERROR_MESSAGE
• WARNING_MESSAGE
• QUESTION_MESSAGE
• PLAIN_MESSAGE 40
Dialog

Jun 23, 2024


• JOptionPane Class
public class JOptionPaneApp {
JOptionPaneApp() {
JFrame frame = new JFrame();
JOptionPane.showMessageDialog(frame, "This is a
JOptionPane message window.", "Error",

Advanced Programming
JOptionPane.ERROR_MESSAGE);
}
public static void main(String[] args) {
new JOptionPaneApp();
}
Example 41
}
Dialog

Jun 23, 2024


//A program which shows several JOptionPane windows on the screen
String name = JOptionPane.showInputDialog(null, "What is ur name?");
// ask the user a yes/no question
int choice = JOptionPane.showConfirmDialog(null, "Do you like java, " +
name + "?");
if (choice == JOptionPane.YES_OPTION) {

Advanced Programming
JOptionPane.showMessageDialog(null, “Thank you!!!");
}
else { // choice == NO_OPTION or CANCEL_OPTION
JOptionPane.showMessageDialog(null, “Please, get ready!");
} Example 42
Menubar, Menu, MenuItem

Jun 23, 2024


For Menubar
• JMenuBar:
 used to crate a menu bar which can contain some menus
 JFrame, JDialog, and JApplet can all have menu bars
 To set Menu Bar use the following method:
setJMenuBar(JMenuBarjbar)

Advanced Programming
 Commonly Used Constructor(s): JMenuBar()
 Commonly Used Method(s):
 JMenuadd(JMenum)
 Int getMenuCount()
 JMenu getMenu(int index)
• Creation of menu bar: JMenuBar mbar = new JMenuBar(); 43
Menubar, Menu, MenuItem

Jun 23, 2024


For MenuItem
• JMenuItem:
 used to create menu’s items which can be placed on to the menu
 Creation of JMenu:
JMenuItem newItem = new JMenuItem(“New”);
 To add menu to the menu bar JMenu.add(newItem);

Advanced Programming
 Commonly Used Constructor(s):
 JMenuItem() , JMenuItem(String label)
 JMenuItem(String label, intmnemonic)
 Commonly Used Method(s):
 void setActionCommand(String command)  void setLabel(String label)
 String getActionCommand()  String getLabel()
 void addActionListener(ActionListeneral)
 void removeActionListener(ActionListeneral) 44
Menubar, Menu, MenuItem

Jun 23, 2024


//A program to create Menu items
JFrame f = new JFrame();
JMenuItem a1, a2;
JMenu menu = new JMenu("Edit");
JMenuBar m1 = new JMenuBar();

Advanced Programming
a1 = new JMenuItem("Cut");
a2 = new JMenuItem("Copy");
menu.add(a1);
menu.add(a2);
m1.add(menu);
f.setJMenuBar(m1); Example 45
Label

Jun 23, 2024


 can be used to display text and/or icon.
 a passive component – does not respond to user input
 Constructors:
JLabel(Icon icon);
JLabel(String str);
JLabel(String str, Icon icon, int align)

Advanced Programming
 Icon & str  icon and text used for label
 To obtain an icon, and object of ImageIcon class has to be
passed as an argument to the Icon parameter.
 Align  horizontal alignment of the text/and or icon
 must be one of the following values: LEFT, RIGHT,
CENTER 46
Button

Jun 23, 2024


 Functionality of a push button
 An icon/string or both can be associated with a button
 Constructors
JButton(Icon str)
JButton(String str)
JButton(String str, Icon icon)

Advanced Programming
 Creation of JButton: JButton jb = new JBtton(label);
 Event Generated:
 when button is pressed ActionEvent object is generated
 To deal with the event, implement ActionListener interface,
register the listener and define the method public void
actionPerformed(ActionEvent) 47
Checkboxes

Jun 23, 2024


• CheckBox: allows to select multiple item from group
 Any number of check boxes in a group — none, some, or all
— can be selected
 Creation of JCheckBox:
JCbeckBox jcb = new JCheckBox();
JCbeckBox jcb = new JCheckBox(Label);
JCbeckBox jcb = new JCheckBox(Label,boolean);

Advanced Programming
 Event Generated:
 It generates one item event and one action event per click
 Usually, you listen only for item events, since they let you
determine whether the click selected or deselected check box
 Creates ItemEvent Object;
 Register with ItemListener interface;
 Implement void itemStateChanged() 48
Checkboxes

Jun 23, 2024


 Constructors
JCheckBox(String) Creates an initially unselected check box with text
JCheckBox(String, Creates a check box with text and specifies whether or not it
boolean) is initially selected.
JCheckBox(Icon) Creates an initially unselected check box with an icon.
JCheckBox(Icon, boolean) Creates a check box with an icon and specifies whether or
not it is initially selected

Advanced Programming
JCheckBox(String, Icon) Creates an initially unselected check box with the specified
text and icon.
JCheckBox(String, Icon, Creates a check box with text and icon, and specifies
boolean) whether or not it is initially selected.
JCheckBox() Creates an initially unselected check box button with no text,
no icon.
49
RadioButtons

Jun 23, 2024


 are groups of buttons in which, by convention, only one button
at a time can be selected
 Swing release JRadioButton and ButtonGroup classes
• JRadioButton: allows to select only 1 item from group items
 Creation of JRadioButton:
JRadioButton jrb = new JRadioButton();
JRadioButton jrb = new JRadioButton(Label);

Advanced Programming
JRadioButton jrb = new JRadioButton(Label,boolean);
• ButtonGroup: used to place multiple buttons into a single
group in which only one button at a time can be selected
 Creation of ButtonGroup:
ButtonGroup bg = new ButtonGroup();
 use its add method to include JRadioButton objects in group
bg.Add(jrb); 50
ComboBox

Jun 23, 2024


 Lets the user choose one of several choices; can have two different
forms
 uneditable combo box – features button & drop-down list of values
 editable – features text field with small button abutting it
 user can type a value in the text field or click the button to display
a drop-down list
 Swing provides a combo box (a combination of a text field and a

Advanced Programming
drop-down list) through the JComboBox class
 Constructors: JComboBox() & JComboBox(Object[])
 Items are added to list of choices via addItem( ) method,
jcb.addItem(item);
obj is the object to be added to the combo box
• Creation of JComboBox: JComboBox jcb = new JComboBox(); 51
ComboBox

Jun 23, 2024


 Event Generated:
Action Event Add an action listener to the combo box.
The listener's actionPerformed method is
Implements ActionListenter
called when the user selects an item from
Register with addActionListener() the combo box's menu or, in an editable
Implement combo box, when the user presses Enter.

Advanced Programming
void actionPerformed(ActionEvent)
ItemEvent Add an item listener to the combo box. The
listener's itemStateChanged() method is
ItemListener
called when the selection state of any of the
addITemListener combo box's items change
void itemStateChanged()
52
TextField

Jun 23, 2024


 A text field can be used to enter or display a string

JTextField firstName = new JTextField(20);


JTextField surName = new JTextField(20);

Advanced Programming
JTextField address = new JTextField(60);
JPanel p=new JPanel();
p.add(firstName);
p.add(surName);
p.add(address);
53
PasswordField

Jun 23, 2024


Advanced Programming
JPasswordField userName = new JPasswordField(20);
JFrame f=new JFrame(“Example 01”);
f.add(userName);//adds the password field to a container
54
List

Jun 23, 2024


 A list is a component that basically performs the same
function as a combo box, but it enables the user to choose a
single value or multiple values.

String[] str = {“Kebede", “Zeleke", “Aster", “Lakech"};


JList list=new JList(str);

Advanced Programming
JPanel p=new JPanel();
p.add(list);

55
Event Handling

Jun 23, 2024


 Events – actions usually triggered by user when interacting with
application
• E.g., buttons, menus, sliders, mouse clicks, ... all generate
events when the user does something with them.
 Events: o Pressing a key
 moving the mouse o sliding the scrollbar thumb

Advanced Programming
 clicking the button o choosing an item from a menu
 Press a button o Selecting an item form a list etc
• import Statements: to use events, you must import:-
• import java.awt.*; AWT
• import java.awt.event.*;
• import javax.swing.*;
• import javax.swing.event.*;
Swing 56
Event Handling

Jun 23, 2024


• Steps to Handle Event in Java
1. Whenever the user clicks the button an event is generated
2. Now the object of the concerned event class will be
automatically created and information about the source and
the event gets populated within the same object
3. The event object is forwarded to the method of the
registered listener class

Advanced Programming
4. Now the method will get executed and returned
 Event handling – mechanism that controls event and decides
what should happen if an event occurs
 activity of capturing events and take appropriate action as
per requirements (e.g. Print a message)
 have the code (known as event handler) that is executed
when an event occurs 57
Event Handling

Jun 23, 2024


 To respond to a button click,
 you need to write the code to process button-clicking action
 button is an event source object, where the action originates
 You need to create an object capable of handling the action
event on a button – called an event listener

Advanced Programming
 Triggering a source fires an event to all its listener(s), and
invoke an appropriate event handler of the listener(s) 58
Event Handling

Jun 23, 2024


 To perform any operation, the component has to listen to
the event that is generated
 But the component can not listen to the events that are
generated
 So, take the help of the listeners which are interfaces

Advanced Programming
which can listen to the events that are generated
 After the listener listens to the generated event, it
delegates (passes) the event information to one of the
method available in that listener
 This process is called as “Event Delegation Model” 59
Event Handling

Jun 23, 2024


 Event Delegation Model has three parts:
• Events
• Events Sources
• Events Listeners

Advanced Programming
60
Event Handling

Jun 23, 2024


 Event Delegation Model has three parts:

Advanced Programming
61
Event Handling

Jun 23, 2024


 Event Delegation Model has three parts:
 Source – an object that causes and generates an event
 some of UI components that can generate events
 E.g., Checkbox: used to generate item events when the
checkbox is selected or deselected

Advanced Programming
 allowed to generate several different types of events
 When an event occurs, all registered listeners are
notified and receive a copy of the event object
 In all cases, notifications are sent to listeners that
register to receive them
62
Event Handling

Jun 23, 2024


 Event Delegation Model has three parts:
 Event – objects that define state change in a source
 All changes that we make when interacting with application
 Change in the state of a component
 signal to the program that something has happened
 triggered either by external user actions (e.g., mouse

Advanced Programming
movements, button clicks and keystrokes) or by internal
program activities (timer)
 The component that creates an event and fires it is called
event source object or source component
 Firing an event means to create an event and delegate
listener to handle the event
 E.g., button is source object for button clicking action event 63
Event Handling

Jun 23, 2024


 Event Delegation Model has three parts:
 Listener – also known as event handler
 Responsible for generating response to an event
 Waits until it receives an event
 Once the event is received, listener process the event and
then returns

Advanced Programming
 object that is invoked when an event triggers
 must be registered with an event source object, and it
must be an instance of an corresponding event-handling
(event-listener) interface - ActionListener interface
 listener interface contains the method(s), known as the event
handler(s), for processing the event 64
Event Handling

Jun 23, 2024


 Event Delegation Model has three parts:
 Listener
• When the user clicks the button,
• JButton object generates an ActionEvent object
• then calls listener object’s actionPerformed() method and
passes that method the event object just generated

Advanced Programming
• Note: a single event source can have multiple listeners
listening for its events
 registration method form: addTypeListener(TypeListener el)
Type: name of event & el: reference to event listener
 ActionListener interface contains the actionPerformed method
for processing the event
 ActionEvent object is passed as parameter to actionPerformed() 65
Event Handling

Jun 23, 2024


public HandleEvent() { Example #1
JButton jbtOK = new JButton("OK");
JPanel panel = new JPanel();
panel.add(jbtOK); Create Listener
add(panel); // Add panel to the frame
OkListenerClass listener1 = new OkListenerClass();

Advanced Programming
jbtOK.addActionListener(listener1);
}
Register Listener
public void actionPerformed(ActionEvent e) {
textField.setText ("Hello World");
}
Process Event 66
Event Handling

Jun 23, 2024


• OkListenerClass listener class implements
ActionListener to process ActionEvent
• object listener1 is an instance of OKListenerClass, which
is registered with the button jbtOK

Advanced Programming
• When OK button is clicked,
actionPerformed(ActionEvent) method in
OKListenerClass is invoked to process the event
67
Event Handling

Jun 23, 2024


 Event Delegation Model has the ff key participants namely:
 Listener Interfaces
User Control addXXXListener method in listener
(interface to be implemented)
Button, TextField, addActionListener() actionPerformed(ActionEvent e)
MenuItem
CheckBox addItemListener() itemstateChanged()

Advanced Programming
key on component addKeyListener() keyPressed(), keyReleased(),
keyTyped()
mouse on component addMouseListener() mouseClicked(), mousePressed(),
mouseReleased(), …
mouse on component addMouseMotionListener() mouseMoved(), mouseDragged()
windowClosing(WindowEvent e),
Frame addWindowListener() windowActivated(),
windowOpened(),..
68
Event Handling

Jun 23, 2024


 Event Delegation Model has the ff key participants namely:
 Listener Interfaces
User Action Source Object Event Type Generated
Click a button JButton ActionEvent
Click a check box JCheckBox ItemEvent, ActionEvent

Advanced Programming
Click a radio button JRadioButton ItemEvent, ActionEvent
Press return on a text field JTextField ActionEvent
Select a new item JComboBox ItemEvent, ActionEvent
Window opened, closed, etc. Window WindowEvent
Mouse pressed, released, etc. Component MouseEvent
Key released, pressed, etc. Component KeyEvent
69
Event Handling

Jun 23, 2024


 Flow of Event Handling
1. User Interaction with component is required to generate an event
2. object of the respective event class is created automatically after
event generation, and it holds all information of the event source
3. newly created object is passed to the methods of registered listener
4. method executes and returns the result
 Code-Approaches

Advanced Programming
 three approaches for performing event handling:
1.Within Class – implemented in single class
2.Other Class – implemented using another class
3.Anonymous Class – implemented in an inner class which does
not contains any name

70
Event Handling

Jun 23, 2024


• Within Class
import java.awt.*; Example
import java.awt.event.*;
class EventHandling extends Frame implements ActionListener {
TextField textField;
EventHandling () {

Advanced Programming
textField = new TextField ();
textField.setBounds (60, 50, 170, 20);
Button button = new Button ("Show");
button.setBounds (90, 140, 75, 40);
button.addActionListener (this);
add (button); add (textField); 71
Event Handling

Jun 23, 2024


• Within Class
setSize (250, 250); Example
setLayout (null);
setVisible (true);
}
public void actionPerformed (ActionEvent e) {

Advanced Programming
textField.setText ("Hello World");
}
public static void main (String args[]) {
new EventHandling ();
}
}
After Clicking, text field value is set to Hello World! 72
Event Handling

Jun 23, 2024


• Other Class
import java.awt.*; Example
import java.awt.event.*;
class MyClass extends Frame{
TextField tf;
MyClass(){
tf = new TextField();

Advanced Programming
tf.setBounds(60,50,170,20); setSize(300,300);
Button b = new Button("click me"); setLayout(null);
setVisible(true);
b.setBounds(100,120,80,30);
}
Outer o = new Outer(this); public static void main(String args[]){
b.addActionListener(o); new MyClass();
add(b); }
add(tf); } 73
Event Handling

Jun 23, 2024


• Other Class
import java.awt.event.*; Example
class Outer implements ActionListener{
MyClass obj;
Outer(MyClass obj){

Advanced Programming
this.obj = obj;
}
public void actionPerformed(ActionEvent e){
obj.tf.setText("Hello, outher here.");
}
} 74
How to build a GUI

Jun 23, 2024


 Create a window in which to display things – usually a JFrame
(for an application), or a JApplet
 Use the setLayout(LayoutManager manager) method to
specify a layout manager
 Create some Components, such as buttons, panels, etc.
 Add your components to your display area, according to your

Advanced Programming
chose layout manager
 Write some Listeners and attach them to your Components
 Interacting gets a Component causes an Event to occur
 listener gets a message when an interacting event occurs, and
executes some code to deal with it
 Display your window
75
How to build a GUI

Jun 23, 2024


 Step 1 and 2: Code for JFrame
import packages
public class MyFirstFrame
{
public static void main(String[] args)
{
JFrame myFr = new JFrame(“my frame”);

Advanced Programming
//size of the frame width and height
myFr.setSize(500,500);
myFr.setVisible(true);
//this v.impt visibility
myFr.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE);
}
}
76
How to build a GUI

Jun 23, 2024


 Step 3: Code for getting content area
JFrame myFr = JFrame(“my frame”)
myFr.setSize(333, 333);
myFr.setVisible(true);
myFr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = myFr.getContentPane();

Advanced Programming
 So, now we are able to add component
in that area of frame 77
How to build a GUI

Jun 23, 2024


 Step 4: Code for Applying layout
JFrame myF = JFrame(“title of frame”)
myFr.setSize(333, 333);
myFr.setVisible(true);
myFr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Advanced Programming
Container c = myFr.getContentPane();
c.setLayout(new FlowLayout());

 There are different method of layout


 Purpose of layout – how the components are appear in frame in
that area of frame
78
How to build a GUI

Jun 23, 2024


 Step 5: Create & add components
JText tf = new JTextField(10);
JButton b1 = new JButton(“My Button”);
JButton b2 = new JButton(“My 2nd Button”);
Button b = new Button(“Awt button”);

Advanced Programming
//Adding component to container
c.add(tf);
c.add(b1);

79
How to build a GUI

Jun 23, 2024


 Step 6: Set size of frame and make it visible
myFr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFr.setSize(200, 150);
myFr.setVisible(true);

Advanced Programming
Output

80
Jun 23, 2024
The End!
Questions, Ambiguities,

Advanced Programming
Doubts, … ???
81

You might also like