GUI Programming:GUI Basics
Graphical User Interface or simply called “GUI” is a general term used in the
software world. A GUI represents an application that has a visual display for the
user with easy to use controls. A GUI generally consists of graphical
components like windows, frames, buttons, labels, etc.
We can use these components to interact with the system or even the outside
world. Java provides many APIs and reusable classes using which we can
develop GUI applications. One of the oldest kits provided by Java is ‘Abstract
Windowing ToolKit” or AWT. All newer APIs or components like Swing;
JavaFX, etc. are based on this AWT.
Prepared by : Dr. Ahmad Jamal
Console programs that we have written so far are equally important but we
should know that all the latest modern desktop applications are graphically
enabled. This means that they have a ready-to-use GUI which makes it easier
for the end-user to use the application with the click of a mouse.
Note that writing GUI is not as easy as drawing some shapes or including
images. The GUI contains a sequence of activities that also trigger some events
that in turn execute some actions on invoking a component or part of a
component like by clicking a button we trigger some actions.
So a GUI application is a framework consisting of graphical components &
events that can be triggered on these components and the actions that execute
as a result of events trigger.
Frameworks usually provide precompiled reusable classes and components
that we can drag and drop in the drawing area and then associate the events
and actions with these components. Prepared by : Dr. Ahmad Jamal
Java provides the following frameworks for GUI programming:
Abstract Windowing Toolkit: This is the oldest framework in Java and it was
first introduced in JDK 1.0. Most of the AWT components are now outdated and
are replaced by Java swing components.
Swing API: This is a set of graphical libraries developed on top of the AWT
framework and is a part of Java Foundation Classes (JFC). Swing has modular
architecture wherein we can use plug-and-play for the components.
JavaFX: The latest framework is available from Java 8 onwards.
Prepared by : Dr. Ahmad Jamal
Graphical User Interface
Graphical User Interface (GUI) offers user interaction via some graphical components. For
example our underlying Operating System also offers GUI via window,frame,Panel, Button,
Textfield, TextArea, Listbox, Combobox, Label, Checkbox etc. These all are known as
components. Using these components we can create an interactive user interface for an
application.
GUI provides result to end user in response to raised events.GUI is entirely based events. For
example clicking over a button, closing a window, opening a window, typing something in a
textarea etc. These activities are known as events.GUI makes it easier for the end user to use
an application. It also makes them interesting.
Examples of GUI based Applications
Automated Teller Machine (ATM)
Airline Ticketing System
Information Kiosks at railway stations
Mobile Applications
Navigation Systems
Every user interface considers the following three main aspects:
UI elements : Thes are the core visual elements the user eventually sees and interacts with.
GWT provides a huge list of widely used and common elements varying from basic to complex
which we will cover in this tutorial.
Layouts: They define how UI elements should be organized on the screen and provide a final
look and feel to the GUI (Graphical User Interface). This part will be covered in Layout chapter.
Behavior: These are events which occur when the user interacts with UI elements.
Advantages of GUI over CUI
GUI provides graphical icons to interact while the CUI (Character User Interface) offers the
simple text-based interfaces.
GUI makes the application more entertaining and interesting on the other hand CUI does not.
GUI offers click and execute environment while in CUI every time we have to enter the
command for a task.
New user can easily interact with graphical user interface by the visual indicators but it is
difficult in Character user interface.
GUI offers a lot of controls of file system and the operating system while in CUI you have to
use commands which is difficult to remember.
Windows concept in GUI allow the user to view, manipulate and control the multiple
applications at once while in CUI user can control one task at a time.
GUI provides multitasking environment so as the CUI also does but CUI does not provide
same ease as the GUI do.
Java Applet
Applet is a special type of program that is embedded in the webpage to
generate the dynamic content. It runs inside the browser and works at
client side.
Prepared by : Dr. Ahmad Jamal
Advantage of Applet
It works at client side so less response time.
Secured
It can be executed by browsers running under many plateforms, including
Linux, Windows, Mac Os etc.
Drawback of Applet
Plugin is required at client browser to execute applet.
Prepared by : Dr. Ahmad Jamal
Lifecycle of Java Applet
Applet is initialized.
Applet is started.
Applet is painted.
Applet is stopped.
Applet is destroyed.
Prepared by : Dr. Ahmad Jamal
Lifecycle methods for Applet:
The java.applet.Applet class 4 life cycle methods and
java.awt.Component class provides 1 life cycle methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of applet.
public void init(): is used to initialized the Applet. It is invoked only once.
public void start(): is invoked after the init() method or browser is maximized. It is used to start the Applet.
public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized.
public void destroy(): is used to destroy the Applet. It is invoked only once.
Prepared by : Dr. Ahmad Jamal
java.awt.Component class
The Component class provides 1 life cycle method of applet.
public void paint(Graphics g): is used to paint the Applet. It
provides Graphics class object that can be used for drawing
oval, rectangle, arc etc.
Prepared by : Dr. Ahmad Jamal
Who is responsible to manage the life cycle of an applet?
Java Plug-in software.
How to run an Applet?
There are two ways to run an applet
By html file.
By appletViewer tool (for testing purpose).
Prepared by : Dr. Ahmad Jamal
Simple example of Applet by html file:
To execute the applet by html file, create an applet and compile it. After that create an html file and place the
applet code in html file. Now click the html file.
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("a simple Applet",150,150);
}
}
Prepared by : Dr. Ahmad Jamal
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
Prepared by : Dr. Ahmad Jamal
Simple example of Applet by appletviewer tool:
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("A simple Applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
Prepared by : Dr. Ahmad Jamal
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java
Prepared by : Dr. Ahmad Jamal
AWT
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI)
or windows-based applications in Java.
Java AWT components are platform-dependent i.e. components are displayed according
to the view of operating system. AWT is heavy weight i.e. its components are using the
resources of underlying operating system (OS).
The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
Prepared by : Dr. Ahmad Jamal
Prepared by : Dr. Ahmad Jamal
Components
All the elements like the button, text fields, scroll bars, etc. are called components. In
Java AWT, there are classes for each component as shown in previous slide diagram. In
order to place every component in a particular position on a screen, we need to add
them to a container.
Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container
such as Frame, Dialog and Panel.
Prepared by : Dr. Ahmad Jamal
Types of containers
1: Window
2: Panel
3: Frame
4: Dialog
Window
The window is the container that have no borders and menu bars. You must use frame,
dialog or another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.
Prepared by : Dr. Ahmad Jamal
Frame
The Frame is the container that contain title bar and border and can have menu bars. It
can have other components like button, text field, scrollbar etc. Frame is most widely
used container while developing an AWT application.
Dialog
The Dialog control represents a top level window with a border and a title used to take
some form of input from the user. It inherits the Window class.
Unlike Frame, it doesn't have maximize and minimize buttons.
Prepared by : Dr. Ahmad Jamal
Prepared by : Dr. Ahmad Jamal
Label
Label is a passive control because it does not create any event when accessed by the
user. The label control is an object of Label. A label displays a single line of read-only text.
However the text can be changed by the application programmer but cannot be changed
by the end user in any way.
Label(String text, int alignment)
Prepared by : Dr. Ahmad Jamal
import java.awt.*;
public class AwtExample{
private void showLabel()
{
Frame frame = new Frame("my frame");
frame.setSize(400,400);
Panel panel = new Panel();
frame.add(panel);
Label label = new Label();
label.setText("First name");
panel.add(label);
frame.setVisible(true);
}
public static void main(String[] args)
{
AwtExample obj = new AwtExample(); Prepared by : Dr. Ahmad Jamal
obj.showLabel();
Prepared by : Dr. Ahmad Jamal
Methods of Components Class
1: frame.setLocation(100,200)
2: frame.setBounds(100,200,700,500)
SetBounds = setLocation + SetSize
3: frame.setBackground(Color.BLUE); // Deprecated
4: frame.isVisible // return boolean value
Prepared by : Dr. Ahmad Jamal
Commonly used UI elements
1. Label:
Label n=new Label("Name:",Label.CENTER);
2. Button
a1=new Button("submit");
a2=new Button("cancel");
3. Checkbox
Checkbox checkbox1 = new Checkbox("Hello World");
4. List
List l1=new List(4);
l1.setBounds(100,100, 75,75);
Prepared by : Dr. Ahmad Jamal
5. Text Field:
TextField na =new TextField(20);
6. Text Area
TextArea area=new TextArea("Welcome to the universe");
area.setBounds(10,30, 300,300);
7. Choice
Choice c=new Choice();
c.setBounds(100,100, 75,75);
c.add("Subject 1");
c.add("Subject 2");
c.add("Subject 3");
c.add("Subject 4");
c.add("Subject 5");
Prepared by : Dr. Ahmad Jamal
Text Field Example
TextField t1 = new TextField("this is example");
TextField t2 = new TextField("this is example 2");
TextField t11 = new TextField(10);
TextField t22 = new TextField("Ahmad",5);
Prepared by : Dr. Ahmad Jamal
Textfield important Methods
IsEditable()
setEditable()
setText()
getText()
Prepared by : Dr. Ahmad Jamal
AWT Example
To create simple AWT example, you need a frame. There are two ways to create a GUI
using Frame in AWT.
1: By extending Frame class (inheritance)
2: By creating the object of Frame class (association)
Prepared by : Dr. Ahmad Jamal
import java.awt.*;
public class AWTExample1 extends Frame {
// initializing using constructor
AWTExample1() {
// creating a button
Button b = new Button("Click Me!!");
// setting button position on screen
b.setBounds(30,100,80,30);
// adding button into frame
add(b);
// frame size 300 width and 300 height
setSize(300,300);
// setting the title of Frame
setTitle("This is our basic AWT example");
// no layout manager
setLayout(null);
// now frame will be visible, by default it is not visible
setVisible(true);
}
public static void main(String args[]) {
AWTExample1 f = new AWTExample1();
}
} Prepared by : Dr. Ahmad Jamal
Prepared by : Dr. Ahmad Jamal
import java.awt.*;
class AWTExample2 {
AWTExample2() {
// creating a Frame
Frame f = new Frame();
// creating a Label
Label l = new Label("Employee id:");
// creating a Button
Button b = new Button("Submit");
// creating a TextField // main method
TextField t = new TextField(); public static void main(String args[]) {
// setting position of above components in the frame
l.setBounds(20, 80, 80, 30); // creating instance of Frame class
t.setBounds(20, 100, 80, 30); AWTExample2 awt_obj = new
b.setBounds(100, 100, 80, 30); AWTExample2();
// adding components into frame
f.add(b); }
f.add(l);
f.add(t); }
// frame size 300 width and 300 height
f.setSize(400,300);
// setting the title of frame
f.setTitle("Employee info");
// no layout
f.setLayout(null);
// setting visibility of frame
f.setVisible(true);
} Prepared by : Dr. Ahmad Jamal
Prepared by : Dr. Ahmad Jamal
SetBounds()
setBounds() method needs four arguments. The first two arguments are x and y
coordinates of the top-left corner of the component, the third argument is the width of the
component and the fourth argument is the height of the component.
Syntax
setBounds(int x-coordinate, int y-coordinate, int width, int height)
Prepared by : Dr. Ahmad Jamal
AWT Graphics
Graphics is an abstract class provided by Java AWT which is used to draw or paint on the components. It
consists of various fields which hold information like components to be painted, font, color etc.
public class MyFrame extends Frame {
public MyFrame()
{
setVisible(true);
setSize(300, 200);
}
public void paint(Graphics g)
{
g.drawRect(100, 100, 100, 50);
}
public static void main(String[] args)
{
new MyFrame();
} Prepared by : Dr. Ahmad Jamal
Other Object which we can draw using Graphics Class
Line
void drawLine(int startX, int startY, int endX, int end)
Rectangle
void drawRect(int x, int y, int width, int height)
void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)
Oval and Circle
void drawOval(int x, int y, int width, int height)
Arc
void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)
Polygon
void drawPolygon(int[] xPoints, int[] yPoints, int nPoints)
Prepared by : Dr. Ahmad Jamal
Exception Handling
The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained.
Prepared by : Dr. Ahmad Jamal
Exception?
Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.
Prepared by : Dr. Ahmad Jamal
Exception Handling?
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application; that is why
we need to handle exceptions.
Prepared by : Dr. Ahmad Jamal
Example: Exception Handling
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Prepared by : Dr. Ahmad Jamal
Major reasons why an exception Occurs
Invalid user input
Device failure
Loss of network connection
Physical limitations (out of disk memory)
Code errors
Opening an unavailable file
Prepared by : Dr. Ahmad Jamal
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, according to Oracle, there are three
types of exceptions namely:
1: Checked Exception
2: Unchecked Exception
3: Error
Prepared by : Dr. Ahmad Jamal
Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error
are known as checked exceptions. For example, IOException, SQLException, etc.
Checked exceptions are checked at compile-time.
Prepared by : Dr. Ahmad Jamal
Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException,
etc. Unchecked exceptions are not checked at compile-time, but they are checked at
runtime.
Prepared by : Dr. Ahmad Jamal
Error
Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.
Prepared by : Dr. Ahmad Jamal
Java Exception Keywords
try The "try" keyword is used to specify a block where we should place an exception
code. It means we can't use try block alone. The try block must be followed by either
catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be followed by finally block
later.
finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It specifies that there may
occur an exception in the method. It doesn't throw an exception. It is always used with
method signature.
Prepared by : Dr. Ahmad Jamal
class Division {
public static void main(String[] args)
{
int a = 10, b = 5, c = 5, result;
try {
result = a / (b - c);
System.out.println("result" + result);
}
catch (ArithmeticException e) {
System.out.println("Exception caught:Division by zero");
}
finally {
System.out.println("I am in final block");
}
}
}
Prepared by : Dr. Ahmad Jamal
Prepared by : Dr. Ahmad Jamal
Java I/O
The java.io package is used to handle input and output operations. Java IO has various
classes that handle input and output sources. A stream is a sequence of data.
Java input stream classes can be used to read data from input sources such as keyboard
or a file. Similarly output stream classes can be used to write data on a display or a file
again.
Prepared by : Dr. Ahmad Jamal
Introduction to I/O Streams in Java
Before understanding IO streams, let us discuss streams. A Stream is also a sequence of
data. It is neither a data structure nor it stores data. Take an example of a river stream,
where water flows from source to destination. Similarly, these are data streams; data
flows through one point to another.
To handle these sequences, we introduce a term called IO streams.
The java.io package helps the user to perform all types of input-output operations. Java
IO package is primarily focused on input-output files, network streams, internal memory
buffers, etc. Data is read and written from Java IO's InputStream and OutputStream
classes.
In other words, IO streams in java help to read the data from an input stream such as a
file and write the data into an output stream such as the standard display or a file again. It
represents source as input and destination as output. It can handle all types of data, from
primitive values to advanced objects.
Prepared by : Dr. Ahmad Jamal
Java I/O
In Java, 3 streams are created for us automatically. All these streams are attached with the console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
Example : System.out.println("simple message");
System.err.println("error message");
int i=System.in.read();//returns ASCII code of 1st character
System.out.println((char)i);//will print the character
Prepared by : Dr. Ahmad Jamal
Input Streams
Streams help us to read data from the input source. It is an abstract class that
provides a programming interface for all input streams.
Input streams are opened implicitly as soon as it is created. To close the input
stream, we use a close() method on the source object.
Output Streams
Output streams help us to write data to a output source(may be file). Similarly
like input streams output streams are also abstract classes that provides a
programming interface for all output streams.
The output stream is opened as soon as it is created and explicitly closed by
using the close() method. Prepared by : Dr. Ahmad Jamal
Error Streams
Error streams are the same as output streams. In some ide’s error is displayed in different
colors (other than the color of output color). It gives output on the console the same as
output streams.
Prepared by : Dr. Ahmad Jamal
Types of Streams in Java
Depending on the types of operations, streams are divided into 2 primary classes.
Input Stream
It is an abstract class of the java.io package and is used to read the data from an input
source. In other words, reading data from files or from a keyboard, etc. We can create an
object of the input stream class using the new keyword. The input stream class has
several types of constructors.
The following code takes the file name as a string, to read the data stored in the file.
InputStream f = new FileInputStream("input.txt");
Prepared by : Dr. Ahmad Jamal
Examples
import java.io.*;
Input.txt
class Main {
public static void main(String[] args) throws IOException {
try {
// loading a file into f variable Hi This is a File
FileInputStream f = new FileInputStream("input.txt"); My Name is Dr. Ahmad
int x = 0;
while ((x = f.read()) != -1) {
System.out.print((char) x);
}
f.close();
} catch (Exception e) {
System.out.println(e); Output
} Hi This is a File
} My Name is Dr. Ahmad
} Prepared by : Dr. Ahmad Jamal
Output Stream
It is an abstract class of the java.io package and writes data to an output resource. In
other words, writing the data into the files. We can create an object of the output stream
class using the new keyword. The output stream class has several types of constructors.
Prepared by : Dr. Ahmad Jamal
import java.io.*;
Example
class Main {
public static void main(String[] args) throws IOException { output.txt
try {
FileOutputStream f = new FileOutputStream("output.txt");
String s = "Java is Object Oriented";
char arr[] = s.toCharArray(); Java is Object Oriented
int x = 0;
while (x < s.length()) {
f.write(arr[x++]);
}
f.close();
} catch (Exception e) {
System.out.println(e);
}
}
} Prepared by : Dr. Ahmad Jamal
Prepared by : Dr. Ahmad Jamal
Java Recursion
Recursion is the technique of making a function call itself. This technique
provides a way to break complicated problems down into simple problems which
are easier to solve.
Example:
public class Recursion {
static void presentScreen() {
presentScreen();
}
}
Prepared by : Dr. Ahmad Jamal
Example
public class MyRecursionExample {
public static void main(String[] args) {
int result = sum(10);
System.out.println(result);
}
public static int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
}
Prepared by : Dr. Ahmad Jamal
Method Overloading
Method Overloading is a Compile time polymorphism. In method overloading,
more than one method shares the same method name with a different signature
in the class. In method overloading, the return type can or can not be the same,
but we have to change the parameter because, in java, we can not achieve the
method overloading by changing only the return type of the method.
Prepared by : Dr. Ahmad Jamal
Method Overloading
import java.io.*; public static void main(String args[])
class MethodOverloadingEx { {
static int add(int a, int b) System.out.println("add() with 2
{ parameters");
return a + b; System.out.println(add(4, 6));
}
static int add(int a, int b, int c) System.out.println("add() with 3
{ parameters");
return a + b + c; System.out.println(add(4, 6, 7));
} } add() with 2 parameters
} 10
add() with 3 parameters
17
Prepared by : Dr. Ahmad Jamal
Method Overriding
Method Overriding is a Run time polymorphism. In method overriding, the
derived class provides the specific implementation of the method that is already
provided by the base class or parent class. In method overriding, the return type
must be the same.
Prepared by : Dr. Ahmad Jamal
import java.io.*;
class Animal {
class MethodOverridingEx {
void eat()
public static void main(String args[])
{
{
System.out.println("eat() method
Dog d1 = new Dog();
of base class");
Animal a1 = new Animal();
System.out.println("eating.");
d1.eat();
}
a1.eat();
}
}
class Dog extends Animal {
}
void eat()
{
System.out.println("eat() method eat() method of derived
of derived class"); class
System.out.println("Dog is Dog is eating.
eating."); eat() method of base class
} eating.
}
Homework
Write the differences between Method Overloading and Method Overriding in
Java.
Prepared by : Dr. Ahmad Jamal
Dynamic binding
Dynamic binding is also referred to as a run-time polymorphism. In this type of
binding, the functionality of the method call is not decided at compile-time. In
other words, it is not possible to decide which piece of code will be executed as
a result of a method call at compile-time.
Overriding a method is a perfect example of dynamic binding in java.
Prepared by : Dr. Ahmad Jamal
Type Safety in Java
The Java language, by design, enforces type safety. It implies that Java
prevents the programs from accessing memory in inappropriate ways by
controlling the memory access of each object. Java does this by using objects
(instantiated from classes) to perform operations.
Prepared by : Dr. Ahmad Jamal
Type Safety in Java
For example, in this Java code, we get an error when we try to cast a String
variable to an integer:
public class TypeCastingExample
{
public static void main(String args[])
{
String d = "Nikhil";
System.out.println("Before conversion: "+d);
//converting string type to int data type
int num = (int) d;
System.out.println("After conversion into int: "+num);
}
}
Prepared by : Dr. Ahmad Jamal
Generics in Java
The Java Generics programming is introduced in J2SE 5 to deal with type-safe
objects. It makes the code stable by detecting the bugs at compile time.
Before generics, we can store any type of objects in the collection, i.e., non-
generic. Now generics force the java programmer to store a specific type of
objects.
Advantage of Java Generics
Type-safety
Type casting is not required
Compile-Time Checking
Prepared by : Dr. Ahmad Jamal
Type-safety
We can hold only a single type of objects in generics. It doesn?t allow to store
other objects.
Without Generics, we can store any type of objects.
List list = new ArrayList();
list.add(10);
list.add("10");
With Generics, it is required to specify the type of object we need to store.
List<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add("10");// compile-time error
Prepared by : Dr. Ahmad Jamal
Type casting is not required
There is no need to typecast the object.
Before Generics, we need to type cast.
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);//typecasting
Prepared by : Dr. Ahmad Jamal
Compile-Time Checking
It is checked at compile time so problem will not occur at runtime. The good
programming strategy says it is far better to handle the problem at compile time
than runtime.
List<String> list = new ArrayList<String>();
list.add("hello");
list.add(32);//Compile Time Error
Prepared by : Dr. Ahmad Jamal
Java Collections Framework
The Collection in Java is a framework that provides an architecture to store and
manipulate the group of objects.
Java Collections can achieve all the operations that you perform on a data such
as searching, sorting, insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework
provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
Prepared by : Dr. Ahmad Jamal
Java Collections Framework
Prepared by : Dr. Ahmad Jamal
Methods of Collection
add
size
remove
iterate
addall
removeall
clear
Prepared by : Dr. Ahmad Jamal
Algorithm Efficiency
Time efficiency - a measure of amount of time for an algorithm to execute.
Space efficiency - a measure of the amount of memory needed for an algorithm
to execute.
Time and space complexity are the two main measures for calculating algorithm
efficiency, determining how many resources are needed on a machine to
process it. Where time measures how long it takes to process the algorithm,
space measures how much memory is used.
Prepared by : Dr. Ahmad Jamal
Searching & Sorting
In Java sorting and searching an element in an array is very easy. Unlike C,
where we have to make all the functions to work, Java has inbuilt functions to do
the same work. To sort an array there is a sort function and to search an
element in a sorted array there is a binarySearch() function.
Syntax for Sorting
Arrays.sort(array_name);
For using Binary search array must be sorted previously
Arrays.binarySearch(array_name, key);
Important Points:
If the input array is not sorted, the results are undefined and negative.
If there are duplicates, there is no guarantee which onePrepared
will be found.
by : Dr. Ahmad Jamal
Finding an element in a sorted array.
import java.util.*;
public class MyFindClass {
public static void main(String args[]) throws Exception
{
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int index = Arrays.binarySearch(array, 2); Output
if (index >= 0)
System.out.println("Element 2 found at index: " Element 2 found at
+ index); index: 1
else
System.out.println("Element not found");
}
}
Prepared by : Dr. Ahmad Jamal
Sorting an array and searching for an element in
the sorted array.
import java.util.*;
public class MySortingSearchingClass {
public static void main(String args[])
{
int array[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
Arrays.sort(array);
int index = Arrays.binarySearch(array, 0); Output
if (index >= 0)
System.out.println("Element 2 found at index: " Element not found
+ index);
else
System.out.println("Element not found");
}
} Prepared by : Dr. Ahmad Jamal
Event-driven Programming
Event-driven programming is a programming paradigm in which the flow of the
program is determined by events such as user actions (mouse clicks, key
presses, button click or hover), sensor outputs, or message passing from other
programs or threads. Event-driven programming is the dominant paradigm used
in graphical user interfaces and other applications (e.g., JavaScript web
applications) that are centered on performing certain actions in response to user
input.
Prepared by : Dr. Ahmad Jamal
Event Handling in Java
Event handling in Java is the procedure that controls an event and performs
appropriate action if it occurs. The code or set of instructions used to implement
it is known as the Event handler.
It consists of two major components:
Event source
Event listener
The source is the object where the event occurs, and the event listener is
responsible for taking appropriate actions when an event occurs. These
Listeners must be registered with the source object in order for the listener to
receive event notifications.
Prepared by : Dr. Ahmad Jamal
Events in Java
Events in Java represent the change in the state of any object. Events
occur when the user interacts with the interface. Clicking a button, moving the
mouse, typing a character, selecting an item from a list, and scrolling the page
are all examples of behaviors that cause an event to occur.
Types of Events in Java:
Foreground Events: These events necessitate the user's direct participation.
They are produced as a result of a user interacting with graphical components in
a Graphical User Interface.
Background Events: Background events are those that require end-user
interaction. Operating system interrupts and hardware or software failures are
examples of background events.
Event handling in Java is the process of controlling an event and taking
appropriate action if one occurs. Prepared by : Dr. Ahmad Jamal
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Random;
public class AwtEventExample {
public AwtEventExample(){
Frame frame = new Frame("AWT Example");
Button mybtn = new Button("Click Me");
mybtn.setBounds(130,150,100,60);
mybtn.setBackground(Color.red);
mybtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mybtn.setBackground(new Color(0,255,51));
mybtn.setForeground(new Color(255,255,0));
mybtn.setFont(new Font("Arial", Font. BOLD, 18));
}
}); Prepared by : Dr. Ahmad Jamal
frame.add(mybtn);
frame.setSize(300,300);
frame.setLayout(null);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e) {
frame.dispose();
}
});
}
public static void main(String[] args) {
AwtEventExample f = new AwtEventExample();
}
}
Prepared by : Dr. Ahmad Jamal
Prepared by : Dr. Ahmad Jamal
Home work
Describe the components of Event Handling in Java.
Events Handler
Event Sources
Event Listeners
Define the Event Classes and Listener Interfaces in Java.
ActionListener
MouseListener
KeyListener
ItemListener
TextListener
MouseWheelListener
WindowListener
ComponentEventListener
ContainerListener etc... Prepared by : Dr. Ahmad Jamal