0% found this document useful (0 votes)
9 views64 pages

VB_Lecture_4

The document provides a comprehensive overview of Object-Oriented Programming (OOP) concepts, focusing on interfaces, abstract classes, and enumerations in Java. It explains the purpose and implementation of interfaces, the characteristics of enums, and the differences between procedural and event-driven programming. Additionally, it covers event handling in Java, including various event types and listener interfaces, along with practical examples and methods for handling events.

Uploaded by

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

VB_Lecture_4

The document provides a comprehensive overview of Object-Oriented Programming (OOP) concepts, focusing on interfaces, abstract classes, and enumerations in Java. It explains the purpose and implementation of interfaces, the characteristics of enums, and the differences between procedural and event-driven programming. Additionally, it covers event handling in Java, including various event types and listener interfaces, along with practical examples and methods for handling events.

Uploaded by

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

Lecture [4]

Dr. Gehad Ismail Sayed


Recap – OOP Concepts
What is interface?
 User interface (UI)
It is a graphical layout of an application. This includes
buttons, images, text entry, screen layout, ..etc.
 User experience (UX)
It is used to determine how easy or difficult to interact
with user interface elements that UI designers have
created
Recap – OOP Concepts
Abstract Classes and Methods
 Data abstraction is the process of hiding certain
details and showing only essential information to
the user.
 Abstraction can be achieved with either abstract
classes or interfaces.
Recap – OOP Concepts
Interfaces
 It is not UI/UX

 A list of method signatures

 An interface is a completely "abstract class"


that is used to group related methods with empty
bodies:

 Similar to abstract class,


 It cannot be instantiated and all of the methods listed
in an interface must be written elsewhere
Interface - Example
Recap – OOP Concepts
Interfaces
 The interface is the only mechanism that allows
achieving multiple inheritance in java.
 To access the interface methods, the interface must be
"implemented" (inherited) by another class with the
implements keyword (instead of extends).
 A class can implements 1:M interface.
Recap – OOP Concepts
Interfaces
 The purpose of an interface is to specify behavior for
other classes
 It is often said that an interface is like a “contract” and
when a class implements an interface it must adhere to
the contract.
Recap – OOP Concepts
Interfaces
 To implement multiple interfaces, separate them
with a comma.
Recap – OOP Concepts
Naming convention to declare interface
class
 Either end with “able”
 or start with “Can”

 Ex. Automotive manufacturing software


Interface vs. Abstract Class
Interface vs. Abstract Class
Realization: is a relationship between the blueprint
class and the object containing its respective
implementation level details.
Interface vs. Abstract Class
 Despite in “Abstract class”, In interface, you don’t have
to add abstract keyword for every method
 All fields in an interface are treated as final and static
 Because they automatically become final, you must provide an
initialization value
 Any class that implements this interface has access to these
variables
Recap – OOP Concepts
 Interface doesn’t have constructors
 Which Java Types can implement interfaces?
 Java class
 Java abstract class
 Java nested class
 Enum
Recap – OOP Concepts
Java Enum Keyword (Enumerations)
 It is a special java type used to define list of constants
(unchangeable variables, like final variables)
 Enums are used when we know all possible values at
compile-time, such as choices on a menu, rounding
modes, command-line flags, etc.
 For example:
 Day {SATURDAY, SUNDAY, MONDAY, TUESDAY,
WEDNESDAY, THURSDAY, FRIDAY}
 Country {EGYPT, JORDON, SYRIA, IRAQ}
 Size { SMALL, MEDIUM, LARGE, EXTRA_LARGE}
 Season {WINTER SPRING, SUMMER, FALL}
Recap – OOP Concepts
Java Enum Keyword (Enumerations)
Recap – OOP Concepts
Java Enum Keyword (Enumerations)
 The enum can be defined within or outside the class
because it is similar to a class.
 To create an enum, use the enum keyword (instead of
class or interface), and separate the constants with a
comma. Note that they should be in uppercase letters
 Syntax:
 enum typName {one or more enum constants}
Ex. enum Level {LOW, MEDIUM, HIGH}
 You can access enum constants with the dot syntax

Ex. Level myVar = Level.MEDIUM;


Recap – OOP Concepts
Java Enum Keyword (Enumerations)
 The following characteristics make enum a ‘special’
class:
 enum constants cannot be overridden
 enum doesn’t support the creation of objects
 enum can’t extend other classes
 enum can implement interfaces like classes
 enum can contain a constructor and it is executed separately for
each enum constant at the time of enum class loading.
 enum can contain both concrete methods and abstract
methods. If an enum class has an abstract method, then each
instance of the enum class must implement it
Recap – OOP Concepts
Java Enum Keyword (Enumerations)
 Ex. Inside a class
public class Main {
enum Level {
LOW,
MEDIUM,
HIGH
}
public static void main(String[] args) {
Level myVar = Level.MEDIUM;
System.out.println(myVar); // MEDIUM
}
}
Recap – OOP Concepts
Java Enum Keyword (Enumerations)
 Ex. Outside a class
enum Level { LOW, MEDIUM, HIGH}
public class Main {
public static void main(String[] args) {
Level myVar = Level.MEDIUM;
switch(myVar) {
case LOW: System.out.println("Low level");
break;
case MEDIUM: System.out.println("Medium level"); //Medium level
break;
case HIGH: System.out.println("High level");
break; }
}}
Recap – OOP Concepts
Java Enum Keyword (Enumerations)
enum Color {
RED, GREEN, BLUE;
// enum constructor called separately for each constant
private Color(){System.out.println("Constructor called for:
"+this.toString()); }
public void colorInfo() { System.out.println("Universal Color"); }
}
public class Test {
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
c1.colorInfo(); }
}
Recap – OOP Concepts
Java Enum Keyword (Enumerations)
enum Color {
RED, GREEN, BLUE;
// enum constructor called separately for each constant
private Color(){System.out.println("Constructor called for:
"+this.toString()); }
public void colorInfo() { System.out.println("Universal Color"); }
}
public class Test {
public static void main(String[] args) Constructor called for : RED
Constructor called for : GREEN
{ Constructor called for : BLUE
Color c1 = Color.RED; RED
Universal Color
System.out.println(c1);
c1.colorInfo(); }
}
Procedural vs. Event-Driven
programming
 Procedural programming is executed in
procedural/sequential order.

 In event-driven programming, code is


executed activation of events.
Event-Driven Programming
 It is a paradigm in which the flow of the program is
determined by events such as user actions (mouse
clicks, key presses), timers, or messages from other
programs/threads.

 It is the dominant paradigm used in graphical user


interfaces.
Events and Listeners
 An event can be defined as a type of signal to the
program that something has happened.
 The event is generated by external user actions such as
mouse movements, mouse button clicks, and
keystrokes, or by the operating system, such as a timer.
 Events are responded to by event listeners.
Types of Events
The events can be broadly classified into two categories −
 Foreground Events − These events require direct interaction of
the user. They are generated as consequences of a person
interacting with the graphical components in the Graphical User
Interface. For example, clicking on a button, moving the mouse,
entering a character through keyboard, selecting an item from
list, scrolling the page, etc.
 Background Events − These events require the interaction of
the end user. Operating system interrupts, hardware or software
failure, timer expiration, and operation completion are some
examples of background events.
Java Event classes and
Listener interfaces
Event Classes Listener Interfaces
ActionEvent ActionListener
MouseEvent MouseListener and MouseMotionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
Event Driven Programming
 Action Event
 Window Event
 Mouse Event
 Key Event
 Focus Event
 Item Event
Swing - ActionEvent Class
 The Java ActionListener is notified whenever
you click on the button or menu item.
 It is notified against ActionEvent.
 The ActionListener interface is found in
java.awt.event package
 It has only one method: actionPerformed().
Methods of ActionListener
interface

Method Signature Description


void actionPerformed(ActionEvent e) Called just after the user performs an
action.
How to write ActionListener?
If you implement the ActionListener class, you
need to follow 3 steps:
1. Implement the ActionListener interface in the
class
2. Register the component with the ActionListener

3. Override the actionPerformed() method


ActionListener - Example
ActionListener - Questions
Question: write a java code that counts the number of clicks and
shows it in a label. Use the below template code.
ActionListener - Questions
Answer
Event Driven Programming
 Action Event
 Window Event
 Mouse Event
 Key Event
 Focus Event
 Item Event
SWING - WindowEvent Class
 The object of this class represents the change in
state of a window.
 This low-level event is generated by a Window
object when it is opened, closed, activated,
deactivated, iconified, or deiconified, or when
the focus is transferred into or out of the
Window.
Methods of WindowListener
interface
Method Signature Description
public abstract void windowActivated It is called when the Window is set
(WindowEvent e); to be an active Window.
public abstract void windowClosed It is called when a window has
(WindowEvent e); been closed as the result of calling
dispose on the window.
public abstract void windowClosing It is called when the user attempts
(WindowEvent e); to close the window from the
system menu of the window.
public abstract void windowDeactivated It is called when a Window is not an
(WindowEvent e); active Window anymore.
Methods of WindowListener
interface
Method Signature Description
public abstract void windowIconified It is called when a window is
(WindowEvent e); changed from a normal to a
minimized state.
public abstract void windowOpened It is called when window is made
(WindowEvent e); visible for the first time.
public abstract void windowDeiconified It is called when a window is
(WindowEvent e); changed from a minimized to a
normal state.
How to write WindowListener?
If you implement the WindowListener class, you
need to follow 3 steps:
1. Implement the WindowListener interface in the
class
2. Register the component with the
WindowListener

3. Override the
WindowListener methods
WindowListener - Example
FrameDemo.Java
WindowListener - Example

NewClass.Java
Swing – Frame Containment
Hierarchy
WindowListener - Questions
Question: write a java code to change the background color of the
window to red when the window is changed from a minimized to a
normal state. Use the below template code.
WindowListener - Questions
Solution
Event Driven Programming
 Action Event
 Window Event
 Mouse Event
 Key Event
 Focus Event
 Item Event
Swing – MouseEvent Class
 Mouse event occurs when a mouse related activity is
performed on a component such as clicking, dragging,
pressing, moving or releasing a mouse etc.

 Objects representing mouse events are created from


MouseEvent class.

 There are two listener interfaces corresponding to the


MouseEvent Class. These include MouseListener and
MouseMotionListener interface.
Methods of MouseEvent
interface
Method Signature Description
Int getClickCount() Returns the number of quick, consecutive clicks
the user has made (including this event). For
example, returns 2 for a double click.
int getX() Return the (x,y) position at which the event
int getY() occurred, relative to the component that fired the
Point getPoint() event.
int getButton() Returns which mouse button, if any, has a
changed state. One of the following constants is
returned: NOBUTTON, BUTTON1, BUTTON2, or
BUTTON3.
Methods of MouseListener
interface
Method Signature Description
void mouseClicked (MouseEvent e) Invoked when the mouse button has
been clicked (pressed and released)
on a component
void mouseEntered (MouseEvent e) Invoked when the mouse pointer
enters a component
void mouseExited (MouseEvent e) Invoked when the mouse pointer exits
a component
void mousePressed (MouseEvent e) Invoked when a mouse button has
been pressed on a component
void mouseReleased (MouseEvent Invoked when a mouse button has
e) been released on a component
How to write MouseListener?
If you implement the MouseListener class, you
need to follow 3 steps:
1. Implement the MouseListener interface in the
class
2. Register the component with the
MouseListener

3.Override the
MouseListener methods
MouseListener Example
FrameDemo.Java
MouseListener Example

NewClass.Java
MouseListener - Questions
Question: write a java code to move NewLabel to the position of the
mouse when it is clicked. Use the below template code.
MouseListener - Questions
Answer
Methods of
MouseMotionListener interface

Method Description
mouseDragged(MouseEvent) Called in response to the user moving the
mouse while holding a mouse button down.
This event is fired by the component that
fired the most recent mouse-pressed event,
even if the cursor is no longer over that
component.
mouseMoved(MouseEvent) Called in response to the user moving the
mouse with no mouse buttons pressed.
This event is fired by the component that's
currently under the cursor.
How to write
MouseMotionListener?
If you implement the MouseMotionListener class,
you need to follow 3 steps:
1. Implement the MouseMotionListener interface

in the class
2. Register the component with the
MouseMotionListener
3. Override the

MouseMotionListener methods
MouseMotionListener -
Example
MouseMotionListener -
Example
2D Graphics - Swing
Method Description
public abstract void is used to draw the specified string.
drawString(String str, int x, int y)
public void drawRect(int x, int y, int draws a rectangle with the specified
width, int height) width and height
public abstract void fillRect(int x, int is used to fill rectangle with the default
y, int width, int height) color and specified width and height.
public abstract void drawOval(int x, is used to draw oval with the specified
int y, int width, int height) width and height.
public abstract void fillOval(int x, int is used to fill oval with the default color
y, int width, int height) and specified width and height.
public abstract void drawLine(int is used to draw line between the
x1, int y1, int x2, int y2) points(x1, y1) and (x2, y2).
2D Graphics - Swing
Method Description
public abstract boolean drawImage(Image is used draw the specified
img, int x, int y, ImageObserver observer) image.
public abstract void drawArc(int x, int y, int is used draw a circular or
width, int height, int startAngle, int arcAngle) elliptical arc.
public abstract void fillArc(int x, int y, int width, is used to fill a circular or
int height, int startAngle, int arcAngle) elliptical arc.
public abstract void setColor(Color c) is used to set the graphics
current color to the specified
color.
public abstract void setFont(Font font) is used to set the graphics
current font to the specified
font.
2D Graphics - Example
Java Swing: Notes
Ways to create a frame:
1. By creating the object of Frame class
(association)

2. By extending Frame class (inheritance)

3. Create a frame using Swing inside main()


Java Swing: Notes
Ways to create a frame:
1. By creating the object of Frame class
(association)
import javax.swing.*;
public class test1
{
JFrame frame;
test1()
{
frame=new JFrame("first way");
JButton button = new JButton("let's see");
button.setBounds(200, 150, 90, 50);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(button);
frame.setSize(500, 600);
frame.setLayout(null);
frame.setVisible(true);
}

public static void main(String[] args)


{ new test1();}
}
Java Swing: Notes
Ways to create a frame:
2. By extending Frame class (inheritance)
Note: we will be inheriting JFrame class to create
JFrame window and hence it won’t be required to
create an instance of JFrame class explicitly.
import javax.swing.*;
public class test2 extends JFrame
{
JFrame frame;
test2()
{
setTitle("this is also a title");
JButton button = new JButton("click");
button.setBounds(165, 135, 115, 55);
add(button);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 500);
setLayout(null);
setVisible(true);
}

public static void main(String[] args)


{ new test2(); }
}
Java Swing: Notes
Ways to create a frame:
3. Create a frame using Swing inside main()

import javax.swing.*;
public class Swing_example
{
public static void main(String[] args)
{
JFrame frame1 = new JFrame();
JButton button1 = new JButton("click");
JButton button2 = new JButton("again click");
button1.setBounds(160, 150 ,80, 80);
button2.setBounds(190, 190, 100, 200);
frame1.add(button1);
frame1.add(button2);
frame1.setSize(400, 500) ;
frame1.setLayout(null);
frame1.setVisible(true);
}
}
64

You might also like