Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

AOT Unit 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 43

UNIT I

Introduction to JavaScript

JavaScript is a lightweight, cross-platform, single-threaded, and interpreted


compiled programming language which is also known as the scripting language for
webpages. It is well-known for the development of web pages, and many non-browser
environments also use it.
JavaScript is a weakly typed language(dynamically typed). JavaScript can be used
for Client-side developments as well as Server-side developments. JavaScript is both an
imperative and declarative type of language. JavaScript contains a standard library of objects,
like Array, Date, and Math, and a core set of language elements like operators, control
structures, and statements.

Client-side: It supplies objects to control a browser and its Document Object Model
(DOM). Like if client-side extensions allow an application to place elements on an HTML form
and respond to user events such as mouse clicks, form input, and page navigation. Useful
libraries for the client side are AngularJS, ReactJS, VueJS, and so many others.
Server-side: It supplies objects relevant to running JavaScript on a server. For if the server-
side extensions allow an application to communicate with a database, and provide continuity
of information from one invocation to another of the application, or perform file manipulations
on a server. The useful framework which is the most famous these days is node.js.
Imperative language In this type of language we are mostly concerned about how it is to be
done. It simply controls the flow of computation. The procedural programming approach,
object, oriented approach comes under this as async await we are thinking about what is to be
done further after the async call.
Declarative programming In this type of language we are concerned about how it is to be
done, basically here logical computation requires. Her main goal is to describe the desired
result without direct dictation on how to get it as the arrow function does.
JavaScript can be added to your HTML file in two ways:
Internal JS: We can add JavaScript directly to our HTML file by writing the code inside the
<script> tag. The <script> tag can either be placed inside the <head> or the <body> tag
according to the requirement.
External JS: We can write JavaScript code in another files having an extension.js and then
link this file inside the <head> tag of the HTML file in which we want to add this code.
Syntax:
<script>
// JavaScript Code
</script>
Example:
HTML
<!DOCTYPE html>
<html lang="en">

<head>
<title>
Basic Example to Describe JavaScript
</title>
</head>

<body>

<!-- JavaScript code can be embedded inside


head section or body section -->
<script>
console.log("Welcome to GeeksforGeeks");
</script>
</body>

</html>

History of JavaScript: It was created in 1995 by Brendan Eich while he was an engineer at
Netscape. It was originally going to be named LiveScript but was renamed. Unlike most
programming languages, JavaScript language has no concept of input or output. It is designed
to run as a scripting language in a host environment, and it is up to the host environment to
provide mechanisms for communicating with the outside world. The most common host
environment is the browser.

Features of JavaScript:

There are following features of JavaScript:

1. All popular web browsers support JavaScript as they provide built-in execution
environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus, it is
a structured programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast
(depending on the operation).
4. JavaScript is an object-oriented programming language that uses prototypes rather than
using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including, Windows, macOS,
etc.
8. It provides good control to the users over the web browsers.
Applications of JavaScript:

Web Development: Adding interactivity and behavior to static sites JavaScript was invented
to do this in 1995. By using AngularJS that can be achieved so easily.
Web Applications: With technology, browsers have improved to the extent that a language
was required to create robust web applications. When we explore a map in Google Maps then
we only need to click and drag the mouse. All detailed view is just a click away, and this is
possible only because of JavaScript. It uses Application Programming Interfaces(APIs) that
provide extra power to the code. The Electron and React are helpful in this department.
Server Applications: With the help of Node.js, JavaScript made its way from client to server
and Node.js is the most powerful on the server side.
Games: Not only in websites, but JavaScript also helps in creating games for leisure. The
combination of JavaScript and HTML 5 makes JavaScript popular in game development as
well. It provides the EaseJS library which provides solutions for working with rich graphics.
Smartwatches: JavaScript is being used in all possible devices and applications. It provides a
library PebbleJS which is used in smartwatch applications. This framework works for
applications that require the Internet for their functioning.
Art: Artists and designers can create whatever they want using JavaScript to draw on HTML
5 canvas, and make the sound more effective also can be used p5.js library.
Machine Learning: This JavaScript ml5.js library can be used in web development by using
machine learning.
Mobile Applications: JavaScript can also be used to build an application for non-web
contexts. The features and uses of JavaScript make it a powerful tool for creating mobile
applications. This is a Framework for building web and mobile apps using JavaScript. Using
React Native, we can build mobile applications for different operating systems. We do not
require to write code for different systems. Write once use it anywhere!

Limitations of JavaScript:
Security risks: JavaScript can be used to fetch data using AJAX or by manipulating tags
that load data such as <img>, <object>, <script>. These attacks are called cross-site script
ing the
details.
Performance: JavaScript does not provide the same level of performance as offered by many
traditional languages as a complex program written in JavaScript would be comparatively
slow. But as JavaScript is used to perform simple tasks in a browser, so performance is not
considered a big restriction in its use.
Complexity: To master a scripting language, programmers must have a thorough knowledge
of all the programming concepts, core language objects, and client and server-side objects
otherwise it would be difficult for them to write advanced scripts using JavaScript.
Weak error handling and type checking facilities: It is a weakly typed language as there is
no need to specify the data type of the variable. So wrong type checking is not performed by
compile.

Why JavaScript is known as a lightweight programming language?


JavaScript is considered lightweight due to the fact that it has low CPU usage, is easy to
implement, and has a minimalist syntax. Minimalist syntax as in, has no data types.
Everything is treated here as an object. It is very easy to learn because of its syntax similar to
C++ and Java.

excess strain on your CPU or RAM. JavaScript runs in the browser even though it has
complex paradigms and logic which means it uses fewer resources than other languages. For
example, NodeJs, a variation of JavaScript not only performs faster computations but also
uses fewer resources than its counterparts such as Dart or Java.
Additionally, when compared with other programming languages, it has fewer in-built
libraries or frameworks, contributing as another reason for it being lightweight. However, this
brings a drawback in that we need to incorporate external libraries and frameworks.

Is JavaScript compiled or interpreted or both?


JavaScript is both compiled and interpreted. In the earlier versions of JavaScript, it used only
the interpreter that executed code line by line and shows the result immediately. But with
time the performance became an issue as interpretation is quite slow. Therefore, in the newer
versions of JS, probably after the V8, the JIT compiler was also incorporated to optimize the
execution and display the result more quickly. This JIT compiler generates a bytecode that is
relatively easier to code. This bytecode is a set of highly optimized instructions.
The V8 engine initially uses an interpreter, to interpret the code. On further executions, the
V8 engine finds patterns such as frequently executed functions, and frequently used variables,
and compiles them to improve performance.
JavaScript is best known for web page development but it is also used in a variety of non-
browser environments.

Javascript Objects

A javaScript object is an entity having state and behavior (properties and method). For
example: car, pen, bike, chair, glass, keyboard, monitor etc.

JavaScript is an object-based language. Everything is an object in JavaScript.

JavaScript is template based not class based. Here, we don't create class to get the object. But,
we direct create objects.

Creating Objects in JavaScript

There are 3 ways to create objects.

1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)

1) JavaScript Object by object literal

The syntax of creating object using object literal is given below:


1. object={property1:value1,property2:value2.....propertyN:valueN}

As you can see, property and value is separated by : (colon).

1. <script>
2. emp={id:102,name:"Shyam Kumar",salary:40000}
3. document.write(emp.id+" "+emp.name+" "+emp.salary);
4. </script>
Output of the above example
102 Shyam Kumar 40000

2) By creating instance of Object

The syntax of creating object directly is given below:

1. var objectname=new Object();

Here, new keyword is used to create object.

1. <script>
2. var emp=new Object();
3. emp.id=101;
4. emp.name="Ravi Malik";
5. emp.salary=50000;
6. document.write(emp.id+" "+emp.name+" "+emp.salary);
7. </script>
Output of the above example
101 Ravi 50000

3) By using an Object constructor

Here, you need to create function with arguments. Each argument value can be assigned in the
current object by using this keyword.

The this keyword refers to the current object.

The example of creating object by object constructor is given below.


1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6. }
7. e=new emp(103,"Vimal Jaiswal",30000);
8.
9. document.write(e.id+" "+e.name+" "+e.salary);
10. </script>

Output of the above example


103 Vimal Jaiswal 30000

Defining method in JavaScript Object

We can define method in JavaScript object. But before defining method, we need to add
property in the function with same name as method.

The example of defining method in object is given below.

1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6.
7. this.changeSalary=changeSalary;
8. function changeSalary(otherSalary){
9. this.salary=otherSalary;
10. }
11. }
12. e=new emp(103,"Sonoo Jaiswal",30000);
13. document.write(e.id+" "+e.name+" "+e.salary);
14. e.changeSalary(45000);
15. document.write("<br>"+e.id+" "+e.name+" "+e.salary);
16. </script>
Output of the above example
103 Sonoo Jaiswal 30000
103 Sonoo Jaiswal 45000

JavaScript Object Methods

The various methods of Object are as follows:

S.No Methods Description

1 Object.assign() This method is used to copy enumerable


and own properties from a source object to
a target object

2 Object.create() This method is used to create a new object


with the specified prototype object and
properties.

3 Object.defineProperty() This method is used to describe some


behavioral attributes of the property.

4 Object.defineProperties() This method is used to create or configure


multiple object properties.

5 Object.entries() This method returns an array with arrays of


the key, value pairs.

6 Object.freeze() This method prevents existing properties


from being removed.

7 Object.getOwnPropertyDescriptor() This method returns a property descriptor


for the specified property of the specified
object.

8 Object.getOwnPropertyDescriptors() This method returns all own property


descriptors of a given object.

9 Object.getOwnPropertyNames() This method returns an array of all


properties (enumerable or not) found.

10 Object.getOwnPropertySymbols() This method returns an array of all own


symbol key properties.

11 Object.getPrototypeOf() This method returns the prototype of the


specified object.

12 Object.is() This method determines whether two


values are the same value.

13 Object.isExtensible() This method determines if an object is


extensible
14 Object.isFrozen() This method determines if an object was
frozen.

15 Object.isSealed() This method determines if an object is


sealed.

16 Object.keys() This method returns an array of a given


object's own property names.

17 Object.preventExtensions() This method is used to prevent any


extensions of an object.

18 Object.seal() This method prevents new properties from


being added and marks all existing
properties as non-configurable.

19 Object.setPrototypeOf() This method sets the prototype of a


specified object to another object.

20 Object.values() This method returns an array of values.

Object Methods
Methods are actions that can be performed on objects.
Object properties can be both primitive values, other objects, and functions.
An object method is an object property containing a function definition.
Property Value
firstName John
lastName Doe
age 50
eyeColor blue
fullName function() {return this.firstName + " " + this.lastName;}
JavaScript objects are containers for named values, called properties and methods.

DHTML stands for Dynamic Hypertext Markup language i.e., Dynamic HTML.

Dynamic HTML is not a markup or programming language but it is a term that combines the
features of various web development technologies for creating the web pages dynamic and
interactive.

The DHTML application was introduced by Microsoft with the release of the 4th version of IE
(Internet Explorer) in 1997.
Components of Dynamic HTML

DHTML consists of the following four components or languages:

o HTML 4.0
o CSS
o JavaScript
o DOM.

HTML 4.0

HTML is a client-side markup language, which is a core component of the DHTML. It defines
the structure of a web page with various defined basic elements or tags.

CSS

CSS stands for Cascading Style Sheet, which allows the web users or developers for controlling
the style and layout of the HTML elements on the web pages.

JavaScript

JavaScript is a scripting language which is done on a client-side. The various browser supports
JavaScript technology. DHTML uses the JavaScript technology for accessing, controlling, and
manipulating the HTML elements. The statements in JavaScript are the commands which tell
the browser for performing an action.

DOM

DOM is the document object model. It is a w3c standard, which is a standard interface of
programming for HTML. It is mainly used for defining the objects and properties of all
elements in HTML.

Uses of DHTML

Following are the uses of DHTML (Dynamic HTML):

o It is used for designing the animated and interactive web pages that are developed in
real-time.
o DHTML helps users by animating the text and images in their documents.
o It allows the authors for adding the effects on their pages.
o It also allows the page authors for including the drop-down menus or rollover buttons.
o This term is also used to create various browser-based action games.
o It is also used to add the ticker on various websites, which needs to refresh their content
automatically.

Features of DHTML

Following are the various characteristics or features of DHTML (Dynamic HTML):

o Its simplest and main feature is that we can create the web page dynamically.
o Dynamic Style is a feature, that allows the users to alter the font, size, color, and
content of a web page.
o It provides the facility for using the events, methods, and properties. And, also provides
the feature of code reusability.
o It also provides the feature in browsers for data binding.
o Using DHTML, users can easily create dynamic fonts for their web sites or web pages.
o With the help of DHTML, users can easily change the tags and their properties.
o The web page functionality is enhanced because the DHTML uses low-bandwidth
effect.

Difference between HTML and DHTML

Following table describes the differences between HTML and DHTML:

HTML (Hypertext Markup language) DHTML (Dynamic Hypertext Markup


language)

1. HTML is simply a markup language. 1. DHTML is not a language, but it is a set of


technologies of web development.

2. It is used for developing and creating 2. It is used for creating and designing the
web pages. animated and interactive web sites or pages.

3. This markup language creates static 3. This concept creates dynamic web pages.
web pages.

4. It does not contain any server-side 4. It may contain the code of server-side
scripting code. scripting.

5. The files of HTML are stored with the 5. The files of DHTML are stored with the
.html or .htm extension in a system. .dhtm extension in a system.

6. A simple page which is created by a 6. A page which is created by a user using the
user without using the scripts or styles HTML, CSS, DOM, and JavaScript
called as an HTML page. technologies called a DHTML page.
7. This markup language does not need 7. This concept needs database connectivity
database connectivity. because it interacts with users.

DHTML JavaScript

JavaScript can be included in HTML pages, which creates the content of the page as dynamic.
We can easily type the JavaScript code within the <head> or <body> tag of a HTML page. If
we want to add the external source file of JavaScript, we can easily add using the <src>
attribute.

Following are the various examples, which describes how to use the JavaScript technology
with the DHTML:

Document.write() Method

The document.write() method of JavaScript, writes the output to a web page.

Example 1: The following example simply uses the document.write() method of JavaScript
in the DHTML. In this example, we type the JavaScript code in the <body> tag.

1. <HTML>
2. <head>
3. <title>
4. Method of a JavaScript
5. </title>
6. </head>
7. <body>
8. <script type="text/javascript">
9. document.write("JavaTpoint");
10. </script>
11. </body>
12. </html>

Output:
JavaScript and HTML event

A JavaScript code can also be executed when some event occurs. Suppose, a user clicks an
HTML element on a webpage, and after clicking, the JavaScript function associated with that
HTML element is automatically invoked. And, then the statements in the function are
performed.

Example 1: The following example shows the current date and time with the JavaScript and
HTML event (Onclick). In this example, we type the JavaScript code in the <head> tag.

1. <html>
2. <head>
3. <title>
4. DHTML with JavaScript
5. </title>
6. <script type="text/javascript">
7. function dateandtime()
8. {
9. alert(Date());
10. }
11. </script>
12. </head>
13. <body bgcolor="orange">
14. <font size="4" color="blue">
15. <center> <p>
16. Click here # <a href="#" onClick="dateandtime();"> Date and Time </a>
17. # to check the today's date and time.
18. </p> </center>
19. </font>
20. </body>
21. </html>

Output:

What is xml
Xml (eXtensible Markup Language) is a mark up language.
XML is designed to store and transport data.

describing data.
XML became a W3C Recommendation on February 10, 1998.
XML is not a replacement for HTML.
XML is designed to be self-descriptive.
XML is designed to carry data, not to display data.
XML tags are not predefined. You must define your own tags.
XML is platform independent and language independent.
Note: Self-describing data is the data that describes both its content and structure.
What is mark-up language
A mark up language is a modern system for highlight or underline a document.
Students often underline or highlight a passage to revise easily, same in the sense of modern
mark up language highlighting or underlining is replaced by tags.

Why xml
Platform Independent and Language Independent: The main benefit of xml is that you can
use it to take data from a program like Microsoft SQL, convert it into XML then share that
XML with other programs and platforms. You can communicate between two platforms
which are generally very difficult.
The main thing which makes XML truly powerful is its international acceptance. Many
corporation use XML interfaces for databases, programming, office application mobile
phones and more. It is due to its platform independent feature.
Features and Advantages of XML
XML is widely used in the era of web development. It is also used to simplify data storage
and data sharing.
The main features or advantages of XML are given below.
1) XML separates data from HTML
If you need to display dynamic data in your HTML document, it will take a lot of work to
edit the HTML each time the data changes.
With XML, data can be stored in separate XML files. This way you can focus on using
HTML/CSS for display and layout, and be sure that changes in the underlying data will not
require any changes to the HTML.
With a few lines of JavaScript code, you can read an external XML file and update the data
content of your web page.
2) XML simplifies data sharing
In the real world, computer systems and databases contain data in incompatible formats.
XML data is stored in plain text format. This provides a software- and hardware-independent
way of storing data.
This makes it much easier to create data that can be shared by different applications.
3) XML simplifies data transport
One of the most time-consuming challenges for developers is to exchange data between
incompatible systems over the Internet.
Exchanging data as XML greatly reduces this complexity, since the data can be read by
different incompatible applications.
4) XML simplifies Platform change
Upgrading to new systems (hardware or software platforms), is always time consuming.
Large amounts of data must be converted and incompatible data is often lost.
XML data is stored in text format. This makes it easier to expand or upgrade to new operating
systems, new applications, or new browsers, without losing data.
5) XML increases data availability
Different applications can access your data, not only in HTML pages, but also from XML
data sources.
With XML, your data can be available to all kinds of "reading machines" (Handheld
computers, voice machines, news feeds, etc), and make it more available for blind people, or
people with other disabilities.
6) XML can be used to create new internet languages
A lot of new Internet languages are created with XML.
Here are some examples:
XHTML
WSDL for describing available web services
WAP and WML as markup languages for handheld devices
RSS languages for news feeds
RDF and OWL for describing resources and ontology
SMIL for describing multimedia for the web
XML Validation
XML file can be validated by 2 ways:
DTD
XSD
DTD (Document Type Definition) and XSD (XML Schema Definition) are used to define
XML structure.

XML DTD

What is DTD

DTD stands for Document Type Definition. It defines the legal building blocks of an XML
document. It is used to define document structure with a list of legal elements and attributes.

Purpose of DTD

Its main purpose is to define the structure of an XML document. It contains a list of legal
elements and define the structure with the help of them.

Checking Validation

Before proceeding with XML DTD, you must check the validation. An XML document is
called "well-formed" if it contains the correct syntax.

A well-formed and valid XML document is one which have been validated against DTD.

Visit http://www.xmlvalidation.com to validate the XML file.

Valid and well-formed XML document with DTD

Let's take an example of well-formed and valid XML document. It follows all the rules of DTD.

employee.xml

1. <?xml version="1.0"?>
2. <!DOCTYPE employee SYSTEM "employee.dtd">
3. <employee>
4. <firstname>vimal</firstname>
5. <lastname>jaiswal</lastname>
6. <email>vimal@javatpoint.com</email>
7. </employee>

In the above example, the DOCTYPE declaration refers to an external DTD file. The content
of the file is shown in below paragraph.

employee.dtd
1. <!ELEMENT employee (firstname,lastname,email)>
2. <!ELEMENT firstname (#PCDATA)>
3. <!ELEMENT lastname (#PCDATA)>
4. <!ELEMENT email (#PCDATA)>

Description of DTD

<!DOCTYPE employee : It defines that the root element of the document is employee.

<!ELEMENT employee: It defines that the employee element contains 3 elements "firstname,
lastname and email".

<!ELEMENT firstname: It defines that the firstname element is #PCDATA typed. (parse-
able data type).

<!ELEMENT lastname: It defines that the lastname element is #PCDATA typed. (parse-able
data type).

<!ELEMENT email: It defines that the email element is #PCDATA typed. (parse-able data
type).

XML DTD with entity declaration

A doctype declaration can also define special strings that can be used in the XML file.

An entity has three parts:

1. An ampersand (&)
2. An entity name
3. A semicolon (;)

Syntax to declare entity:

1. <!ENTITY entity-name "entity-value">

XML Schema

XML schema is a language which is used for expressing constraint about XML documents.
There are so many schema languages which are used now a days for example Relax- NG and
XSD (XML schema definition).

An XML schema is used to define the structure of an XML document. It is like DTD but
provides more control on XML structure.
Checking Validation

An XML document is called "well-formed" if it contains the correct syntax. A well-formed and
valid XML document is one which have been validated against Schema.

Visit http://www.xmlvalidation.com to validate the XML file against schema or DTD.

XML Schema Example

Let's create a schema file.

employee.xsd

1. <?xml version="1.0"?>
2. <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
3. targetNamespace="http://www.javatpoint.com"
4. xmlns="http://www.javatpoint.com"
5. elementFormDefault="qualified">
6. <xs:element name="employee">
7. <xs:complexType>
8. <xs:sequence>
9. <xs:element name="firstname" type="xs:string"/>
10. <xs:element name="lastname" type="xs:string"/>
11. <xs:element name="email" type="xs:string"/>
12. </xs:sequence>
13. </xs:complexType>
14. </xs:element>
15.
16. </xs:schema>

Let's see the xml file using XML schema or XSD file.

employee.xml

1. <?xml version="1.0"?>
2. <employee
3. xmlns="http://www.javatpoint.com"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xsi:schemaLocation="http://www.javatpoint.com employee.xsd">
6. <firstname>vimal</firstname>
7. <lastname>jaiswal</lastname>
8. <email>vimal@javatpoint.com</email>
9. </employee>

Description of XML Schema

<xs:element name="employee"> : It defines the element name employee.

<xs:complexType> : It defines that the element 'employee' is complex type.

<xs:sequence> : It defines that the complex type is a sequence of elements.

<xs:element name="firstname" type="xs:string"/> : It defines that the element 'firstname'


is of string/text type.

<xs:element name="lastname" type="xs:string"/> : It defines that the element 'lastname' is


of string/text type.

<xs:element name="email" type="xs:string"/> : It defines that the element 'email' is of


string/text type.

XML Schema Data types

There are two types of data types in XML schema.

1. simpleType
2. complexType

simpleType

The simpleType allows you to have text-based elements. It contains less attributes, child
elements, and cannot be left empty.

complexType

The complexType allows you to hold multiple attributes and elements. It can contain additional
sub elements and can be left empty.

Document Object Model


1.

The document object represents the whole html document.


When html document is loaded in the browser, it becomes a document object. It is the root
element that represents the html document. It has properties and methods. By the help of
document object, we can add dynamic content to our web page.

As mentioned earlier, it is the object of window. So

1. window.document

Is same as

1. document

According to W3C - "The W3C Document Object Model (DOM) is a platform and language-
neutral interface that allows programs and scripts to dynamically access and update the
content, structure, and style of a document."

Properties of document object

Let's see the properties of document object that can be accessed and modified by the document
object.
Methods of document object

We can access and change the contents of document by its methods.

The important methods of document object are as follows:

Method Description

write("string") writes the given string on the doucment.

writeln("string") writes the given string on the doucment with newline character at the end.

getElementById() returns the element having the given id value.

getElementsByName() returns all the elements having the given name value.

getElementsByTagName() returns all the elements having the given tag name.

getElementsByClassName() returns all the elements having the given class name.

Accessing field value by document object

In this example, we are going to get the value of input text by user. Here, we are
using document.form1.name.value to get the value of name field.

Here, document is the root element that represents the html document.

form1 is the name of the form.

name is the attribute name of the input text.

value is the property, that returns the value of the input text.

Let's see the simple example of document object that prints name with welcome message.

1. <script type="text/javascript">
2. function printvalue(){
3. var name=document.form1.name.value;
4. alert("Welcome: "+name);
5. }
6. </script>
7.
8. <form name="form1">
9. Enter Name:<input type="text" name="name"/>
10. <input type="button" onclick="printvalue()" value="print name"/>
11. </form>

Output of the above example


Enter Name:

The core Presenting XML mark-up language is currently being further developed in a
companion project, Serving XML. Anyone interested primarily in the command line
examples should use the Serving XML software instead.

Presenting XML is a Java web application framework for presenting HTML, PDF, WML
etc. in a device independent manner. It aims to achieve a complete separation of content and
presentation. It supports various kinds of content including XML files, dynamic content, SQL
result sets and flat files. It provides a declarative way for applying filters and XSLT
transforms to a stream of XML content in a pipeline. It allows user defined filters and
serializers written as Java plug-ins. It is component based and extendible.

Presenting XML may be used as a command line tool or as a framework for a servlet-based
web application. Simple examples with XML, XSLT, and Java are included in the
distribution. There are command line examples for converting flat files to XML (and vice
versa), for converting SQL results to XML, for applying a sequence of XSLT transforms and
SAX filters in a pipeline, and for setting up streaming filters.

There is a sample web application that illustrates how to build a simple shopping cart.

The last Presenting XML file distribution may be downloaded from SourceForge. It includes
Java source code and ant build files as well as binary jar files, a sample web application, and
run scripts. It includes api documentation and a user guide. It also includes a number of third
party jar files including Saxon (also Xalan), Apache Xerces, Sun's Multi-Schema XML
Validator, and the Apache fop pdf driver. It includes everything for running the sample web
application except the Java JDK and a web server.

Presenting XML requires Java JDK 1.3 or later (it will not work with earlier versions.) It
also requires a web server. The examples are configured to work with Jakarta Tomcat 4.0,
which may be downloaded and installed separately. The WML sample pages require a WAP
browser. A free WAP browser emulator may be obtained from OPENWAVE.

Java Applet

Note:
java.applet package package has been deprecated in Java 9 and later versions,as
applets are no longer widely used on the web.

1. AWT(Abstract Window Toolkit)


2. Swing
Throwback of making GUI application:
Java was launched on 23-Jan-1996(JDK 1.0) and at that time it only supported
CUI(Character User Interface) application. But in 1996 VB(Visual Basic) of Microsoft was
preferred for GUI programming. So the Java developers in hurry(i.e within 7 days) have
given the support for GUI from Operating System(OS). Now, the components like button,
etc. were platform-dependent(i.e in each platform there will be different size, shape button).
But they did the intersection of such components from all platforms and gave a small
library which contains these intersections and it is available in AWT(Abstract Window

-
company which developed Java) contracted with other company known as

are produced by Java itself. Therefore now it is platform-independent as well as some


additional features have also been added which were not in AWT technology. So we can
say that SWING is much more advanced as compared to AWT technology.
What is Applet?
An applet is a Java program that can be embedded into a web page. It runs inside the web
browser and works at client side. An applet is embedded in an HTML page using the
APPLET or OBJECT tag and hosted on a web server.
Applets are used to make the website more dynamic and entertaining.
Important points :
1. All applets are sub-classes (either directly or indirectly)
of java.applet.Applet class.
2. Applets are not stand-alone programs. Instead, they run within either a web
browser or an applet viewer. JDK provides a standard applet viewer tool called
applet viewer.
3. In general, execution of an applet does not begin at main() method.
4. Output of an applet window is not performed by System.out.println(). Rather it is
handled with various AWT methods, such as drawString().
Life cycle of an applet :

It is important to understand the order in which the various methods shown in the above
image are called. When an applet begins, the following methods are called, in this
sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )

1. init( ) : The init( ) method is the first method to be called. This is where you should
initialize variables. This method is called only once during the run time of your applet.
2. start( ) : The start( ) method is called after init( ). It is also called to restart an applet
after it has been stopped. Note that init( ) is called once i.e. when the first time an applet is
loaded whereas start( )
onscreen. So, if a user leaves a web page and comes back, the applet resumes execution
at start( ).
3. paint( ) : The paint( ) method is called each time an AWT-
redrawn. This situation can occur for several reasons. For example, the window in which
the applet is running may be overwritten by another window and then uncovered. Or the
applet window may be minimized and then restored.
paint( ) is also called when the applet begins execution. Whatever the cause, whenever the
applet must redraw its output, paint( ) is called.
The paint( ) method has one parameter of type Graphics. This parameter will contain the
graphics context, which describes the graphics environment in which the applet is running.
This context is used whenever output to the applet is required.
Note: This is the only method among all the method mention above, which is

public void paint(Graphics g)


where g is an object reference of class Graphic.
Now the Question Arises:
Q. In the prototype of paint() method, we have created an object reference without creating
its object. But how is it possible to create object reference without creating its object?
Ans. Whenever we pass object reference in arguments then the object will be provided by
its caller itself. In this case the caller of paint() method is browser, so it will provide an
object. The same thing happens when we create a very basic program in normal Java
programs. For Example:
public static void main(String []args){}
Here we have created an object reference without creating its object but it still runs because

4. stop( ) : The stop( ) method is called when a web browser leaves the HTML document
containing the applet when it goes to another page, for example. When stop( ) is called,
the applet is probably running. You should use stop( )
run when the applet is not visible. You can restart them when start( ) is called if the user
returns to the page.
5. destroy( ) : The destroy( ) method is called when the environment determines that your
applet needs to be removed completely from memory. At this point, you should free up any
resources the applet may be using. The stop( ) method is always called before destroy( ).
Creating Hello World applet :

Java
// A Hello World Applet
// Save file as HelloWorld.java

import java.applet.Applet;
import java.awt.Graphics;

// HelloWorld class extends Applet


public class HelloWorld extends Applet
{
// Overriding paint() method
@Override
public void paint(Graphics g)
{
g.drawString("Hello World", 20, 20);
}

Explanation:
1. The above java program begins with two import statements. The first import
statement imports the Applet class from applet package. Every AWT-
based(Abstract Window Toolkit) applet that you create must be a subclass
(either directly or indirectly) of Applet class. The second statement import
the Graphics class from AWT package.
2. The next line in the program declares the class HelloWorld. This class must be
declared as public because it will be accessed by code that is outside the
program. Inside HelloWorld, paint( ) is declared. This method is defined by the
AWT and must be overridden by the applet.
3. Inside paint( ) is a call to drawString( ), which is a member of
the Graphics class. This method outputs a string beginning at the specified X,Y
location. It has the following general form:
void drawString(String message, int x, int y)
Here, message is the string to be output beginning at x,y. In a Java window, the upper-left
corner is location 0,0. The call to drawString( )

Notice that the applet does not have a main( ) method. Unlike Java programs, applets do
not begin execution at main( ) main( ) method.
Instead, an applet begins execution when the name of its class is passed to an applet viewer
or to a network browser.
Running the HelloWorld Applet :
After you enter the source code for HelloWorld.java, compile in the same way that you
have been compiling java programs(using javac command). However, running HelloWorld
with the java command will generate an error because it is not an application.
java HelloWorld

Error: Main method not found in class HelloWorld,


please define the main method as:
public static void main(String[] args)
There are two standard ways in which you can run an applet :
1. Executing the applet within a Java-compatible web browser.
2. Using an applet viewer, such as the standard tool, applet-viewer. An applet
viewer executes your applet in a window. This is generally the fastest and
easiest way to test your applet.
Each of these methods is described next.
1. Using java enabled web browser : To execute an applet in a web browser we have to
write a short HTML text file that contains a tag that loads the applet. We can use APPLET
or OBJECT tag for this purpose. Using APPLET, here is the HTML file that executes
HelloWorld :
<applet code="HelloWorld" width=200 height=60>
</applet>
The width and height statements specify the dimensions of the display area used by the
applet. The APPLET tag contains several other options. After you create this html file, you
can use it to execute the applet.
NOTE : Chrome and Firefox no longer supports NPAPI (technology required for Java
applets). Refer here
2. Using appletviewer : This is the easiest way to run an applet. To execute HelloWorld
with an applet viewer, you may also execute the HTML file shown earlier. For example, if
the preceding HTML file is saved with
RunHelloWorld.html, then the following command line will run HelloWorld :
appletviewer RunHelloWorld.html

3. appletviewer with java source file : If you include a comment at the head of your Java
source code file that contains the APPLET tag then your code is documented with a
prototype of the necessary HTML statements, and you can run your compiled applet merely
by starting the applet viewer with your Java source code file. If you use this method, the
HelloWorld source file looks like this :
Java

//code to illustrate paint


//method gets called again
//and again
import java.applet.*;// used
//to access showStatus()
import java.awt.*;//Graphic
//class is available in this package
import java.util.Date;// used
//to access Date object
public class GFG extends Applet
{
public void paint(Graphics g)
{
Date dt = new Date();
super.showStatus("Today is" + dt);
//in this line, super keyword is
// avoidable too.
}
}

>
With this approach, first compile HelloWorld.java file and then simply run the below
command to run applet :
appletviewer HelloWorld
To prove above mentioned point,i.e paint is called again and again.
:

write something in it, we use method showStatus() whose prototype is


public void showStatus(String)

By default background color is white.


Event Handling
An event can be defined as changing the state of an object or behavior by performing
actions. Actions can be a button click, cursor movement, keypress through keyboard or
page scrolling, etc.
The java.awt.event package can be used to provide various event classes.
Classification of Events
Foreground Events
Background Events

Types of Events
1. Foreground Events
Foreground events are the events that require user interaction to generate, i.e., foreground
events are generated due to interaction by the user on components in Graphic User Interface
(GUI). Interactions are nothing but clicking on a button, scrolling the scroll bar, cursor
moments, etc.
2. Background Events
Events that require interactions of users to generate are known as background events.
Examples of these events are operating system failures/interrupts, operation completion,
etc.
Event Handling
It is a mechanism to control the events and to decide what should happen after an
event occur. To handle the events, Java follows the Delegation Event model.
Delegation Event model
It has Sources and Listeners.

Delegation Event Model

Source: Events are generated from the source. There are various sources like
buttons, checkboxes, list, menu-item, choice, scrollbar, text components,
windows, etc., to generate events.
Listeners: Listeners are used for handling the events generated from the source.
Each of these listeners represents interfaces that are responsible for handling
events.
To perform Event Handling, we need to register the source with the listener.
Registering the Source With Listener
Different Classes provide different registration methods.
Syntax:
addTypeListener()

where Type represents the type of event.


Example 1: For KeyEvent we use addKeyListener() to register.
Example 2:that For ActionEvent we use addActionListener() to register.
Event Classes in Java
Event Class Listener Interface Description

An event that indicates that a


component-defined action occurred
ActionEvent ActionListener
like a button click or selecting an item
from the menu-item list.

The adjustment event is emitted by an


AdjustmentEvent AdjustmentListener
Adjustable object like Scrollbar.

An event that indicates that a


ComponentEvent ComponentListener component moved, the size changed
or changed its visibility.

When a component is added to a


container (or) removed from it, then
ContainerEvent ContainerListener
this event is generated by a container
object.

These are focus-related events, which


FocusEvent FocusListener include focus, focusin, focusout, and
blur.

An event that indicates whether an


ItemEvent ItemListener
item was selected or not.

An event that occurs due to a


KeyEvent KeyListener sequence of keypresses on the
keyboard.

The events that occur due to the user


MouseListener &
MouseEvent interaction with the mouse (Pointing
MouseMotionListener
Device).

An event that specifies that the mouse


MouseWheelEvent MouseWheelListener
wheel was rotated in a component.

An event that occurs when an


TextEvent TextListener
text changes.

An event which indicates whether a


WindowEvent WindowListener
window has changed its status or not.
Note: As Interfaces contains abstract methods which need to implemented by the registered
class to handle events.
Different interfaces consists of different methods which are specified below.
Listener Interface Methods

ActionListener actionPerformed()

AdjustmentListener adjustmentValueChanged()

componentResized()
componentShown()
ComponentListener
componentMoved()
componentHidden()

componentAdded()
ContainerListener
componentRemoved()

focusGained()
FocusListener
focusLost()

ItemListener itemStateChanged()

keyTyped()
KeyListener keyPressed()
keyReleased()

mousePressed()
mouseClicked()
MouseListener mouseEntered()
mouseExited()
mouseReleased()

mouseMoved()
MouseMotionListener
mouseDragged()

MouseWheelListener mouseWheelMoved()

TextListener textChanged()

windowActivated()
WindowListener windowDeactivated()
windowOpened()
Listener Interface Methods

windowClosed()
windowClosing()
windowIconified()
windowDeiconified()

Flow of Event Handling


1. User Interaction with a component is required to generate an event.
2. The object of the respective event class is created automatically after event
generation, and it holds all information of the event source.
3. The newly created object is passed to the methods of the registered listener.
4. The method executes and returns the result.
Code-Approaches
The three approaches for performing event handling are by placing the event handling code
in one of the below-specified places.
1. Within Class
2. Other Class
3. Anonymous Class
Note: Use any IDE or install JDK to run the code, Online compiler may throw errors due
to the unavailability of some packages.
Event Handling Within Class
Java

// Java program to demonstrate the


// event handling within the class

import java.awt.*;
import java.awt.event.*;

class GFGTop extends Frame implements ActionListener {

TextField textField;

GFGTop()
{
// Component Creation
textField = new TextField();

// setBounds method is used to provide


// position and size of the component
textField.setBounds(60, 50, 180, 25);
Button button = new Button("click Here");
button.setBounds(100, 120, 80, 30);

// Registering component with listener


// this refers to current instance
button.addActionListener(this);

// add Components
add(textField);
add(button);

// set visibility
setVisible(true);
}

// implementing method of actionListener


public void actionPerformed(ActionEvent e)
{
// Setting text to field
textField.setText("GFG!");
}

public static void main(String[] args)


{
new GFGTop();
}
}

Output

After Clicking, the text field value is set to GFG!

Explanation
1. Firstly extend the class with the applet and implement the respective listener.
2. Create Text-Field and Button components.
3. Registered the button component with respective event. i.e. ActionEvent by
addActionListener().
4. In the end, implement the abstract method.
Event Handling by Other Class
Java

// Java program to demonstrate the


// event handling by the other class

import java.awt.*;
import java.awt.event.*;

class GFG1 extends Frame {

TextField textField;

GFG2()
{
// Component Creation
textField = new TextField();

// setBounds method is used to provide


// position and size of component
textField.setBounds(60, 50, 180, 25);
Button button = new Button("click Here");
button.setBounds(100, 120, 80, 30);

Other other = new Other(this);

// Registering component with listener


// Passing other class as reference
button.addActionListener(other);

// add Components
add(textField);
add(button);

// set visibility
setVisible(true);
}

public static void main(String[] args)


{
new GFG2();
}
}
Java

/// import necessary packages


import java.awt.event.*;

// implements the listener interface


class Other implements ActionListener {

GFG2 gfgObj;

Other(GFG1 gfgObj) {
this.gfgObj = gfgObj;
}

public void actionPerformed(ActionEvent e)


{
// setting text from different class
gfgObj.textField.setText("Using Different Classes");
}
}

Output

Handling event from different class

Event Handling By Anonymous Class


Java

// Java program to demonstrate the


// event handling by the anonymous class

import java.awt.*;
import java.awt.event.*;

class GFG3 extends Frame {

TextField textField;

GFG3()
{
// Component Creation
textField = new TextField();

// setBounds method is used to provide


// position and size of component
textField.setBounds(60, 50, 180, 25);
Button button = new Button("click Here");
button.setBounds(100, 120, 80, 30);

// Registering component with listener anonymously


button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
// Setting text to field
textField.setText("Anonymous");
}
});

// add Components
add(textField);
add(button);

//make size viewable


setSize(300,300);
// set visibility
setVisible(true);
}

public static void main(String[] args)


{
new GFG3();
}
}
Output

Handling anonymously

AWT in java
Java AWT or Abstract Window Toolkit is an API used for developing GUI(Graphic User
Interfaces) or Window-Based Applications in Java. Java AWT is part of the Java Foundation
Classes (JFC) that provides a way to build platform-independent graphical applications.
In this AWT tutorial, you will learn the basics of the AWT, including how to create
windows, buttons, labels, and text fields. We will also learn how to add event listeners to
components so that they can respond to user input.
By the end of this tutorial, you will have a good understanding of the AWT and be able to
create simple GUIs in Java.
Java AWT Basics
Java AWT (Abstract Window Toolkit) is an API used to create Graphical User Interface
(GUI) or Windows-based Java programs and Java AWT components are platform-
dependent, which means they are shown in accordance with the operating view.
AWT is heavyweight, which means that its components consume resources from the
underlying operating system (OS). The java.awt package contains AWT API classes such
as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List, and so on.
Points about Java AWT components
i. Components of AWT are heavy and platform dependent
ii. AWT has less control as the result can differ because of components are platform
dependent.
Why AWT is Platform Independent?
The Java AWT utilizes the native platform subroutine to create API components such as
TextField, CheckBox, and buttons. This results in a different visual format for these
components on different platforms such as Windows, MAC OS, and Unix. The reason for
this is that each platform has a distinct view of its native components. AWT directly calls
this native subroutine to create the components, resulting in an AWT application resembling
a Windows application on Windows OS, and a Mac application on the MAC OS. In simpler
terms, the AWT appearance adapts to the platform it is running on.
AWT is platform independent even after the AWT components are platform dependent
because of the points mentioned below:
1. JVM (Java Virtual Machine):
As Java Virtual Machine is platform dependent
2. Abstract APIs:
AWT provides an abstract layer for GUI. Java applications interact with AWT through
Abstract API which are platform independent. Abstract API allows Java to isolate platform-
specific details, making code portable across different systems.
3. Platform-Independent Libraries:
The Libraries of AWT are written in Java which they are totally platform-independent.
Because of this, it ensures that AWT functionality remains consistent across different
environments.
Java AWT Hierarchy

Components: AWT provides various components such as buttons, labels, text


fields, checkboxes, etc used for creating GUI elements for Java Applications.
Containers: AWT provides containers like panels, frames, and dialogues to
organize and group components in the Application.
Layout Managers: Layout Managers are responsible for arranging data in the
containers sone of the layout managers are BorderLayout, FlowLayout, etc.
Event Handling: AWT allows the user to handle the events like mouse clicks,
key presses, etc. using event listeners and adapters.
Graphics and Drawing: It is the feature of AWT that helps to draw shapes,
insert images and write text in the components of a Java Application.
Note: Container can be added inside another container as it is type of component.
Types of Containers in Java AWT
There are four types of containers in Java AWT:
1. Window: Window is a top-level container that represents a graphical window or
dialog box. The Window class extends the Container class, which means it can
contain other components, such as buttons, labels, and text fields.
2. Panel: Panel is a container class in Java. It is a lightweight container that can be
used for grouping other components together within a window or a frame.
3. Frame: The Frame is the container that contains the title bar and border and can
have menu bars.
4. Dialog: A dialog box is a temporary window an application creates to retrieve
user input.
Java AWT Label
Java AWT Button
Java AWT TextField
Java AWT Checkbox
Java AWT CheckboxGroup
Java AWT Choice
Java AWT List
Java AWT Canvas
AWT Scrollbar
Java AWT MenuItem & Menu
Java AWT PopupMenu
Java AWT Panel
Java AWT Toolkit
1. Java AWT Label
Syntax of AWT Label
public class Label extends Component implements Accessible

AWT Label Class Constructors


There are three types of Java AWT Label Class
1. Label():
Creates Empty Label.
2. Label(String str):
Constructs a Label with str as its name.
3. Label(String str, int x):
Constructs a label with the specified string and x as the specified alignment
2. Java AWT Button
AWT Button is a control component with a label that generates an event when clicked on.
Button Class is used for creating a labeled button that is platform-independent.
Syntax of AWT Button
public class Button extends Component implements Accessible

Java AWT Button Class Constructors


There are two types of Button class constructors as mentioned below:
1. Button( ):
Creates a Button with no label i.e. showing an empty box as a button.
2. Button(String str):
Creates a Button with String str as a label. For example if button with
show click here as the value.
3. Java AWT TextField
Syntax of AWT TextField:
public class TextField extends TextComponent

TextField Class constructors


There are TextField class constructors are mentioned below:
1. TextField():
Constructs a TextField component.
2. TextField(String text):
Constructs a new text field initialized with the given string str to be displayed.
3. TextField(int col):
Creates a new text field(empty) with the given number of columns (col).
4. TextField(String str, int columns):
Creates a new text field(with String str in the display) with the given number of columns
(col).
4. Java AWT Checkbox
Syntax of AWT Checkbox:
public class Checkbox extends Component implements ItemSelectable, Accessible

Checkbox Class Constructors


There are certain constructors in the AWT Checkbox class as mentioned below:
1. Checkbox():
Creates a checkbox with no label.
2. Checkbox(String str):
Creates a checkbox with a str label.
3. Checkbox(String str, boolean state, CheckboxGroup group):
Creates a checkbox with the str label, and sets the state in the mentioned group.
5. Java AWT CheckboxGroup
CheckboxGroup Class is used to group together a set of Checkbox.
Syntax of AWT CheckboxGroup:
public class CheckboxGroup extends Object implements Serializable

Note: CheckboxGroup enables the use of radio buttons in AWT.


6. Java AWT Choice
The object of the Choice class is used to show a popup menu of choices.
Syntax of AWT Choice:
public class Choice extends Component implements ItemSelectable, Accessible

AWT Choice Class constructor


Choice(): It creates a new choice menu.
7. Java AWT List
The object of the AWT List class represents a list of text items.
Syntax of Java AWT List:
public class List extends Component implements ItemSelectable, Accessible

AWT List Class Constructors


The List of class constructors is defined below:
1. List():
Creates a new list.
2. List(int row):
Creates lists for a given number of rows(row).
3. List(int row, Boolean Mode)
Ceates new list initialized that displays the given number of rows.
8. Java AWT Canvas
Syntax of AWT Canvas:
public class Canvas extends Component implements Accessible

Canvas Class Constructors


1. Canvas():
Creates new Canvas.
2. Canvas(GraphicConfiguration config):
It creates a new Canvas with the given Graphic configuration.
9. AWT Scrollbar
Syntax of AWT Scrollbar:
public class Scrollbar extends Component implements Adjustable, Accessible

Java AWT Scrollbar Class Constructors


There are three constructor classes in Java mentioned below:
1.Scrollbar():
It Creates a new vertical Scrollbar in the Application.
2.Scrollbar(intorientation):
Creates a new vertical Scrollbar with the given orientation.
3.Scrollbar(int orientation, int value, int visible, int mini, int maxi):
Creates a new scrollbar with the orientation mentioned with value as the default value and
[mini, maxi] as the lower and higher limit.
10. Java AWT MenuItem & Menu
MenuItem class adds a simple labeled menu item on the menu. The MenuItem class allows
you to create individual items that can be added to menus. And Menu is a component used
to create a dropdown menu that can contain a list of MenuItem components.
Syntax of Java AWT MenuItem
public class MenuItem extends MenuComponent implements Accessible

Syntax of Java AWT Menu


public class Menu extends MenuItem implements MenuContainer, Accessible

Java AWT PopupMenu is a component that is used for dynamically popping up a menu that
appears when the user right-clicks or performs any other action on a component.
Syntax of AWT PopupMenu
public class PopupMenu extends Menu implements MenuContainer, Accessible

12. Java AWT Panel


Java AWT Panel is a container class used to hold and organize graphical components in a
Java Application.
Syntax of Java AWT Panel:
public class Panel extends Container implements Accessible

13. Java AWT Toolkit


Java AWT Toolkit class provides us with a platform-independent way to access various
system resources and functionalities. Subclasses of Toolkit are used to bind various
components.
Syntax of Java AWT Toolkit
public abstract class Toolkit extends Object

Event Handling Components Java AWT


Here are some of the event handling components in Java:
Java ActionListener
Java MouseListener
Java MouseMotionListener
Java ItemListener
Java KeyListener
Java WindowListener
Close AWT Window
1. Java ActionListener
Java ActionListner is a interface which responds to the actions performed by the
components like buttons, menu items ,etc.
Syntax of Java ActionListener:
public class ActionListenerExample Implements ActionListener

There is only methods associated with ActionListner class that is actionPerformed().


Syntax of actionPerformed() method:
public abstract void actionPerformed(ActionEvent e);

2. Java MouseListener
Java MouseListner is a interface that responds to the actions performed by mouse events
generated by the user. Example: mouse clicks , mouse movements, etc.
There are 5 Methods associated with MouseListner:
1. mouseClicked(MouseEvent e):
Responds to mouse buttons when clicked on a component in the Application.
2. mousePressed(MouseEvent e):
Responds to mouse button is Pressed on a component in the Application.
3. mouseReleased(MouseEvent e):
Responds to Mouse button released after being pressed over a component in the
Application.
4. mouseEntered(MouseEvent e):
Responds to the situation when a Mouse cursor enters the bounds of a component in an
Application.
5. mouseExited(MouseEvent e):
Responds to the situation when a Mouse cursor exits a bounds.
3. Java MouseMotionListener
Java MouseMotionListner is a interface which is notified when mouse is moved or dragged.
It contains two Methods mentioned below:
1. mouseDragged(MouseEvent e):
Responds when the mouse is dragged with mouse button clicked over a component in
Application.
2. mouseMoved(MouseEvent e):
Responds when the mouse is moved over a component in Application.
4. Java ItemListener
Java ItemListner is an interface which handles events related to item selection and
deselection those that occur with checkboxes, radio buttons, etc. There is only one Method
associated with ItemListner that is itemStateChanged(). This method provides information
about the event, i.e. source of the event and the changed state.
Syntax of itemStateChanged() method:
itemStateChanged(ItemEvent e)

5. Java KeyListener
Java KeyListner is an interface in Java notified whenever you change the state of key or can
be said for key related events.
Syntax of KeyListener:
public interface KeyListener extends EventListener
There are three methods associated with KeyListner as mentioned below:
1. keyPressed (KeyEvent e):
Responds to the event when key is pressed.
2. keyReleased (KeyEvent e):
Responds to the event when the key is released.
3. keyTyped (KeyEvent e):
Responds to the key has been typed.
6. Java WindowListener
Java WindowListener is a interface used for handling events related to window actions.
Events like opening , closing, minimizing, etc are handled using WindowListener.
Syntax of WindowListener
public interface WindowListener extends EventListener

There are seven methods associated with WindowListener as mentioned below:


1. windowActivated (WindowEvent e):
Responds when window is first opened
2. windowClosed (WindowEvent e):
Responds when the user attempts to close the window
3. windowClosing (WindowEvent e):
Responds after a window has been closed
4. windowDeactivated (WindowEvent e):
Responds when a window is minimized
5. windowDeiconified (WindowEvent e):
Responds when a window is restored from a minimized state
6. windowIconified (WindowEvent e):
Responds when a window is activated
7. windowOpened (WindowEvent e):
Responds when a window loses focus
7. Java Adapter classes
Java adapter classes provide the default implementation of listener interfaces.
8. Close AWT Window
At the end we will need to Close AWT Window, So to perform this task we will use
dispose() method. This method releases the resources associated with the window and also
removes it from the screen.
1. Hello World in Java AWT
Hello, World is was the first step in learning Java. So, let us program our first Program in
Java AWT as Hello World using Labels and Frames.
Below is the implementation of the above method:
Java

// Java AWT Program for Hello World


import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

// Driver Class
public class AWT_Example {
// main function
public static void main(String[] args)
{
// Declaring a Frame and Label
Frame frame = new Frame("Basic Program");
Label label = new Label("Hello World!");

// Aligning the label to CENTER


label.setAlignment(Label.CENTER);

// Adding Label and Setting


// the Size of the Frame
frame.add(label);
frame.setSize(300, 300);

// Making the Frame visible


frame.setVisible(true);

// Using WindowListener for closing the window


frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
}

2. Java AWT Program to create Button


Below is the implementation of the Java AWT Program to create a Button:
Java

// Java AWT Program for Button


import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

// Driver Class
public class Button_Example {
// main function
public static void main(String[] args)
{
// Creating instance of frame with the label
Frame frame = new Frame("Example 2");
// Creating instance of button with label
Button button = new Button("Click Here");

// Setting the position for the button in frame


button.setBounds(80, 100, 64, 30);

// Adding button to the frame


frame.add(button);

// setting size, layout and visibility of frame


frame.setSize(300, 300);
frame.setLayout(null);
frame.setVisible(true);

// Using WindowListener for closing the window


frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
}

You might also like