[Go to site: main page, start]

0% found this document useful (0 votes)
8 views91 pages

Java Programming Digital Notes

The document contains lecture notes for a Java Programming course aimed at B.Tech III Year students. It outlines course objectives, unit topics covering OOP concepts, inheritance, exception handling, applets, and GUI programming, along with relevant textbooks and reference materials. The notes also include a detailed index and explanations of fundamental Java programming concepts such as data types, variables, operators, and expressions.

Uploaded by

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

Java Programming Digital Notes

The document contains lecture notes for a Java Programming course aimed at B.Tech III Year students. It outlines course objectives, unit topics covering OOP concepts, inheritance, exception handling, applets, and GUI programming, along with relevant textbooks and reference materials. The notes also include a detailed index and explanations of fundamental Java programming concepts such as data types, variables, operators, and expressions.

Uploaded by

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

(R22A0552) JAVAPROGRAMMING

LECTURE NOTES
[Link] III YEAR – I SEM (R22)
(2024-2025)

DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING

MALLA REDDY COLLEGE OF ENGINEERING & TECHNOLOGY


(Autonomous Institution – UGC, Govt. of India)
(Affiliated to JNTUH, Hyderabad, Approved by AICTE - Accredited by NBA & NAAC – ‘A’ Grade -
ISO 9001:2015 Certified)
Maisammaguda, Dhulapally (Post Via. Hakimpet), Secunderabad – 500100, Telangana State, INDIA.
MALLA REDDY COLLEGE OF ENGINEERING & TECHNOLOGY

DEPARTMENT OF EEE

COURSE OBJECTIVES:
1. To create Java programs that leverage the object-oriented features of the Java language,such as
encapsulation, inheritance and polymorphism; Use data types, arrays and strings.
2. Implement error-handling techniques using exception handling,
3. To know about Applets and Event Handling
4. Create and event-driven GUI using AWT components.
5. To learn Multithreading concepts
UNIT-I
OOP Concepts, History of Java, Java buzzwords, Data types, Variables, Constants, Scope and Life
time of variables, Operators, Type conversion and casting, Control Flow Statements, simple java
programs, concepts of classes, objects, arrays, strings, constructors, methods, access control, this
keyword, overloading methods and constructors, garbage collection, recursion
UNIT – II
Inheritance – Types of Inheritance, super keyword, and preventing inheritance: final classes and
methods.
Polymorphism – Dynamic binding, method overriding, abstract classes and methods.
Interfaces-Interfaces Vs Abstract classes, defining an interface, implement interfaces, extending
interface.
Packages- Defining, creating and accessing a package, importing packages.
UNIT-III
Exception handling - Benefits of exception handling, exception hierarchy, Classification of
exceptions - checked exceptions and unchecked exceptions, usage of try, catch, throw, throws and
finally, built in exceptions.
Multi-threading- Differences between multi-threading and multitasking, thread life cycle, creating
threads, synchronizing threads
UNIT-IV
Applets – Concepts of Applets, differences between applets and applications, life cycle of an
applet, types of applets, creating applets, passing parameters to applets. Event Handling: Events,
Handling mouse and keyboard events. Files- Streams, Byte streams, Character streams, Text
input/output.
UNIT-V
GUI Programming with Java – AWT class hierarchy, AWT controls - Labels, button, text field, check
box, and graphics. Layout Manager – Layout manager types: border, grid and flow. Swing –
Introduction, limitations of AWT, Swing vs AWT.
TEXT BOOKS:
1. Java- The Complete Reference, 7th edition, Herbert schildt,TMH.
2. Understanding OOP with Java, updated edition, T. Budd, Pearsoneducation.
3. Core Java an integrated approach, dreamtech publication, [Link].

REFERENCE BOOKS:
1. Java for Programmers, [Link] and [Link], PEA (or) Java: How to Program,[Link] and
[Link], PHI
2. Object Oriented Programming through Java, P. Radha Krishna, Universities Press
Course Outcomes:
An understanding of the principles and practice of object-oriented programming anddesign in the
construction of robust, maintainable programs which satisfy theirrequirements;
1. A competence to design, write, compile, test and execute straightforward programsusinga high-
level language;
2. An awareness of the need for a professional approach to design and the importanceofgood
documentation to the finished programs.
3. Be able to make use of members of classes found in the Java API.
4. Demonstrate the ability to employ various types of constructs and a hierarchy of Javaclasses to
provide solution to a given set of requirements.
MALLA REDDY COLLEGE OF ENGINEERING &TECHNOLOGY
DEPARTMENT OF EEE

INDEX

S. No Unit Topic Page no


1 I OOP Concepts 1

2 I History of Java buzzwords 3

3 I Comments, Data types, Variables, Constants 4

4 I Scope and Lifetime of variables 5

5 I Operators, Type conversion and casting, 7

6 I Control flow Statements 8

7 I Simple java programs, 11

8 I Cconcepts of classes,Object,array,Strings 14

9 I Constructors, methods. 15

10 I access control, this keyword, 19


overloading methods and constructors, garbage
11 I collection, recursion 23
Inheritance – Types of Inheritance ,super keyword
12 II 26
preventing inheritance: final classes and methods
13 II 27

14 II Polymorphism – dynamic binding, method overriding, 30

15 II Abstract classes and methods. 31


Interfaces- Interfaces Vs Abstract classes, defining
16 II 33
an interface, implement interfaces
17 II Packages- Defining, creating and accessing a package, 33

18 II Importing packages. 34

19 III Exception handling - Benefits of exception handling, 35

20 III Exception hierarchy, Classification of exceptions 36


21 III checked exceptions and unchecked exceptions, Usage of 36
try,
III Catch, throw,throws and finally, built in exceptions 37
23
24 III Multi-threading- Differences between multi-threading and
38
multitasking
25 III thread life cycle, creating threads, synchronizing threads 39
S. No Unit Topic Page no

Applets – Concepts of Applets,


26 IV 41
Differences between applets and applications,
27 IV 42

28 IV life cycle of an applet, types of applets, 43


creating applets, passing parameters to applets
29 IV 44
Event Handling: Events, Handling mouse and keyboard
30 IV 47
events
Files- Streams, Byte streams, Character streams,
31 IV Text input/output 62
GUI Programming with Java – AWT class hierarchy,
32 V 57
AWT controls - Labels, button, text field heck box, and
33 V 59
graphics.
Layout Manager – Layout manager types: border, grid and
34 V 61
flow.
Swing – Introduction, limitations of AWT, Swing vs AWT.
35 V 77
MRCET JAVA NOTES [Link] -I SEM-2024-2025

MALLA REDDY COLLEGE OF ENGINEERING &TECHNOLOGY


DEPARTMENT OF EEE
Unit-1
OOP Concepts

Object Oriented Programming is a paradigm that provides many concepts such as


inheritance, data binding, polymorphism etc.

Simula is considered as the first object-oriented programming language. The programming


paradigm where everything is represented as an object is known as truly object-oriented
programming language.

Smalltalk is considered as the first truly object-oriented programming language.

OOPs (Object Oriented Programming System)

Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects.
It simplifies the softwaredevelopment and maintenance by providing someconcepts:

 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation

Object

Any entity that has state and behavior is known as an object. For example: chair,
pen, table,keyboard, bike etc. It can be physical and logical.

Class

Collection of objects is called class. It is a logical entity.

Inheritance

When one object acquires all the properties and behaviours of parent object i.e.
known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.

JAVA PROGRAMMING Page 1


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Polymorphism

When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.

In java, we use method overloading and method overriding to achieve polymorphism. Another

example can be to speak something e.g. cat speaks meaw, dog barks woof [Link]

Hiding internal details and showing functionality is known as abstraction. For example: phone
call, we don't know the internal processing.

In java, we use abstract class and interface to achieve abstraction.

Encapsulation

Binding (or wrapping) code and data together into a single unit is known as encapsulation.
For example: capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class because
allthe data members are private here.

Java Programming- History of Java

The history of java starts from Green Team. Java team members (also knownas Green Team),
initiated a revolutionary task to develop a language for digital devices such as set-top boxes,
televisionsetc.

For the green team members, it was an advance concept at that time. But, it was suited for internet
programming. Later, Java technology as incorporated by Netscape.

Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc.
There are given the major points that describes the history of java.
1. James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
project in June 1991. The small team of sun engineers called Green Team.
2. Originally designed for small, embedded systems in electronic appliances like set-
topboxes.
3. Firstly, it was called "Greentalk" by James Gosling and file extension [Link].
4. After that, it was called Oak and was developed as a part of the Green
project.

JAVA PROGRAMMING Page 2


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Java Version History

There are many java versions that has been released. Current stable release of Java is
Java SE 8.

 JDK Alpha and Beta (1995)

 JDK 1.0 (23rd Jan, 1996)

 JDK 1.1 (19th Feb, 1997)

 J2SE 1.2 (8th Dec, 1998)

 J2SE 1.3 (8th May, 2000)

 J2SE 1.4 (6th Feb, 2002)

 J2SE 5.0 (30th Sep,2004)


 Java SE 6 (11th Dec,2006)

 Java SE 7 (28th July, 2011)

 Java SE 8 (18th March,2014)

List of Buzzwords in Java

 Simple
 Object-Oriented
 Secure
 Platform-Independent
 Garbage Collection
 Robust
 Scalable
 Multithreading
 Performance
 Portable

JAVA PROGRAMMING Page 3


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Data Types

Data types represent the different values to be stored in the variable. In java, there are two types
of data types:
 Primitive datatypes
 Non-primitive datatypes

Java Variable Example: Add Two Numbers

class Simple
{
public static void main(String[] args)
{
int a=10; int b=10; int c=a+b;
[Link](c);
}
}
Output: 20

Variables and Data Types in Java

Variable is a name of memory location. There are three types of variables in java: local,
instance and static.

There are two types of data types in java: primitive and non-primitive.

Types of Variable

There are three types of variables in java:

 localvariable
 instancevariable
 staticvariable

JAVA PROGRAMMING Page 4


MRCET JAVA NOTES [Link] -I SEM-2024-2025

1) LocalVariable

A variable which is declared inside the method is called local variable.

2) Instance Variable

A variable which is declared inside the class but outside the method, is called instance variable . It
is not declared as static.

3) Staticvariable

A variable that is declared as static is called static variable. It cannot be local. We will have
detailed learning of these variables in next chapters.

Example to understand the types of variables in java

classA
{
int data=50;
static variable void method()
{
int n=90;//local variable
}
}//end of class

Constants in Java

A constant is a variable which cannot have its value changed after declaration. It uses the 'final'
keyword.

Syntax

modifier final dataType variableName = value; //global constant


modifier static final dataType variableName = value; //constant within a c
Scope and Life Time of Variables :

The scope of a variable defines the section of the code in which the variable is visible. As a
general rule, variables that are defined within a block are not accessible outside that block. The
lifetime of a variable refers to how long the variable exists before it isdestroyed. Destroying
variables refers to deallocating the memory that was allotted to the variables when declaring it. We
have written a few classes till now. You might have observed that not all variables are the same.
The ones declared in the body of a method were different from those that were declared in the
class itself. There are three types of variables: instance variables, formal parameters or local
variables and localvariables.

JAVA PROGRAMMING Page 5


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Instance variables

Instance variables are those that are defined within a class itself and not in any method or
constructor of the class. They are known as instance variables because every instance of the
class (object) contains a copy of these variables. The scope of instance variables is determined by
the access specifier that is applied to these variables. We have already seen about it earlier. The
lifetime of these variables is the same as the lifetime of the object to which it belongs. Object once
created do not exist for ever. They are destroyed by the garbage collector of Java when there are
no more reference to that object. We shall see about Java's automatic garbage collector later on.
Argument variables

These are the variables that are defined in the header oaf constructor or a method. The scope of
these variables is the method or constructor in which they are defined. The lifetime is limited to the
time for which the method keeps executing. Once the method finishes execution, these variables
are destroyed.

Local variables
o A local variable is the one that is declared within a method or a constructor (not in the
header). The scope and lifetime are limited to the methoditself.
o One important distinction between these three types of variables is that access specifiers
can be applied to instance variables only and not to argument or local variables.
o In addition to the local variables defined in a method, we also have variables that are
defined in bocks life an if block and an else block. The scope and is the same as that of the
block itself.

Operators in java

Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc. There
are many types of operators in java which are given below:

 UnaryOperator,

 ArithmeticOperator,

 shiftOperator,

 RelationalOperator,

 BitwiseOperator,

 LogicalOperator,

 Ternary Operatorand

 AssignmentOperator.

JAVA PROGRAMMING Page 6


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Operators Hierarchy

Expressions

Expressions are essential building blocks of any Java program, usually created to produce a new
value, although sometimes an expression simply assigns a value to a variable. Expressions are
built using values, variables, operators and method calls.

Types of Expressions

While an expression frequently produces a result, it doesn't always. There are three types of
expressions in Java:
 Those that produce a value, i.e. the result of (1 + 1)

 Those that assign a variable, for example (v =10)

 Those that have no result but might have a "side effect" because an expression can
include a wide range of elements such as method invocations or increment operators that
modify the state (i.e. memory) of a program.

JAVA PROGRAMMING Page 7


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Java Type casting and Type conversion


Widening or Automatic Type Conversion
Widening conversion takes place when two data types are automatically converted. This happens
when:
 The two data types arecompatible.
 When we assign value of a smaller data type to a bigger datatype.

For Example, in java the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or boolean. Also, char and boolean are not
compatible with each other.

Narrowing or Explicit Conversion


If we want to assign a value of larger data type to a smaller data type we perform explicit type
casting or narrowing.
 This is useful for incompatible data types where automatic conversion cannot bedone.
 Here, target-type specifies the desired type to convert the specified valueto.

Control Flow Statements

The control flow statements in Java allow you to run or skip blocks of code when special conditions
are met.
The “if” Statement
The “if” statement in Java works exactly like in most programming languages. With
the help of “if” you can choose to execute a specific block of code when a predefined
condition is met. The structure of the “if” statement in Java looks like this:
Syntax

if(condition) {
// execute this code
}

JAVA PROGRAMMING Page 8


MRCET JAVA NOTES [Link] -I SEM-2024-2025

The condition is Boolean. Boolean means it may be true or false. For example you may put a
mathematical equation as condition. Look at this full example:

 Less than: a < b


 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b
 Equal to a == b
 Not Equal to: a != b

You can use these conditions to perform different actions for different decisions.

Java has the following conditional statements:

 Use if to specify a block of code to be executed, if a specified condition is true


 Use else to specify a block of code to be executed, if the same condition is false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed

You already know that Java supports the usual logical conditions from mathematics:

 Less than: a < b


 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b
 Equal to a == b
 Not Equal to: a != b

You can use these conditions to perform different actions for different decisions.

Java has the following conditional statements:

 Use if to specify a block of code to be executed, if a specified condition is true


 Use else to specify a block of code to be executed, if the same condition is false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed

Example :

public class Main


{
public static void main(String[] args)
{
int x = 20;
int y = 18;
if (x > y) {
[Link]("x is greater than y");
}
}
}
Output:

JAVA PROGRAMMING Page 9


MRCET JAVA NOTES [Link] -I SEM-2024-2025

x is greater than y

if else statement
public class Main {
public static void main(String[] args)
{
int time = 20;
if (time < 18)
{
[Link]("Good day.");
}
else {
[Link]("Good evening.");
}
}
}

Output:

Good evening.

Else if statements

public class Main


{
public static void main(String[] args)
{
int time = 22;
if (time < 10) {
[Link]("Good morning.");
}
else if (time < 18)
{
[Link]("Good day.");
}
else
{
[Link]("Good evening.");
}
}
}

Java Switch Statements


Instead of writing many if..else statements, you can use the switch statement.

JAVA PROGRAMMING Page 10


MRCET JAVA NOTES [Link] -I SEM-2024-2025

The switch statement selects one of many code blocks to be executed:

Syntax
Switch(expression)
{
Case x:
// code block
Break;
Case y:
// code block
Break;
default :
//code block
}

Example
public class Main
{
public static void main(String[] args)
{
int day = 4;
switch (day)
{
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thursday");
break;
case 5:
[Link]("Friday");
break;
case 6:
[Link]("Saturday");
break;
case 7:
[Link]("Sunday");
break;
}
}
}
JAVA PROGRAMMING Page 11
MRCET JAVA NOTES [Link] -I SEM-2024-2025

Java While Loop


The while loop loops through a block of code as long as a specified condition is true:
Syntax
while(condition)
{
// code block to be executed
}
Example:
public class Main
{
public static void main(String[] args)
{
int i = 0;
while (i < 5)
{
[Link](i);
i++;
}
}
}
Output:
0
1
2
3
4

Java Do/While Loop


The do/while loop is a variant of the while loop. This loop will execute the code block once, before
checking if the condition is true, then it will repeat the loop as long as the condition is true.
Syntax
do
{
// code block to be executed
} while(condition)
Example
public class Main
{
public static void main(String[] args)
{
int i = 0;
do {
[Link](i);
i++;
}
while (i < 5);
}
}

JAVA PROGRAMMING Page 12


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Output:
0
1
2
3
4

Java For Loop


When you know exactly how many times you want to loop through a block of code, use the for loop
instead of a while loop:
Syntax:
for(statements1,statements 2,statement 3)
{
//code block to be executed
}
Example:
public class Main
{
public static void main(String[] args)
{
for (int i = 0; i < 5; i++)
{
[Link](i);
}
}
}
Output:
0
1
2
3
4

Arrays
Java provides a data structure, the array, which stores a fixed-size sequential collection of elements
of the same type. An array is used to store a collection of data, but it is often more useful to think of
an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare
one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to
represent individual variables.
This tutorial introduces how to declare array variables, create arrays, and process arrays using
indexed variables.

JAVA PROGRAMMING Page 13


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Declaring Array Variables:


To use an array in a program, you must declare a variable to reference the array, and you
must specify the type of array the variable can reference. Here is the syntax for declaring an
array variable:
dataType[] arrayRefVar; // preferred way. or
dataType arrayRefVar[]; // works but not preferred way.

Example:
public class Main
{
public static void main(String[] args)
{
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
[Link]([Link]);
}
}
Output:
4
Example:
public class Main
{
public static void main(String[] args)
{
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};

float avg, sum = 0;

int length = [Link];

for (int age : ages)


{
sum += age;
}
avg = sum / length;

[Link]("The average age is: " + avg);


}
}
Output:
The average age is: 40.75

Java Classes and Objects


Java is an object-oriented programming language.
Everything in Java is associated with classes and objects, along with its attributes and methods. For
example: in real life, a car is an object. The car has attributes, such as weight and color,
and methods, such as drive and brake.
A Class is like an object constructor, or a "blueprint" for creating objects.

JAVA PROGRAMMING Page 14


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Create a Class
To create a class, use the keyword class:

public class Main


{
int i=5;
)
Create an Object
In Java, an object is created from a class. We have already created the class named Main, so now
we can use this to create objects.
To create an object of Main, specify the class name, followed by the object name, and use the
keyword new:
Example:
public class Main
{
int x = 5;

public static void main(String[] args)


{
Main myObj = new Main();
[Link](myObj.x);
}
}
Output:
5

Constructors

Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data
for the object that is why it is known as constructor.

There are basically two rules defined for the constructor.


1. Constructor name must be same as its classname

2. Constructor must have no explicit returntype

Types of java constructors

There are two types of constructors:


1. Default constructor (no-argconstructor)
2. Parameterizedconstructor
Enter your name: Nakul Jain Welcome Nakul Jain

Syntax of default constructor:


1. <class_name>(){}

JAVA PROGRAMMING Page 15


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time
of object creation.

classBike1
{
Bike1()
{
[Link]("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}
}
Output:Bike is created

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two parameters. We can
have any number of parameters in the constructor.

classStudent4
{
int id;
String name;
student4(int i,String n)
{
id = i;
name = n;
}
void display()
{
[Link](id+" "+name);
}
public static void main(String args[])
{
student4 s1 = new student4(111,"Karan");
student4 s2 = new student4(222,"Aryan");
[Link]();
[Link]();
}
}
Output:

111Karan
222Aryan

JAVA PROGRAMMING Page 16


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Java -Methods

A Java method is a collection of statements that are grouped together to perform an operation. When
you call the [Link]() method, for example, the system actually executes several
statements in order to display a message on the console.
Now you will learn how to create your own methods with or without return values, invoke a method
with or without parameters, and apply method abstraction in the program design.

Creating Method
Considering the following example to explain the syntax of a method −
Syntax
public static int methodName(int a, int b)
{
// body
}
Here,
 public static −modifier

 int − returntype

 methodName − name of the method

 a, b − formalparameters

 int a, int b − list ofparameters

Method definition consists of a method header and a method body. The same is shown in the
following syntax −
Syntax
modifier returnType nameOfMethod (Parameter List)
{
// method body
}

The syntax shown above includes –

 modifier− It defines the access type of the method and it is optional touse.
 returnType− Method may return avalue.
 nameOfMethod− This is the method name. The method signature consists of themethod
name and the parameter list.
 Parameter List − The list of parameters, it is the type, order, and number of parameters of a
method. These are optional, method may contain zeroparameters.
 method body − The method body defines what the method does with thestatements.

JAVA PROGRAMMING Page 17


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Call by Value and Call by Reference in Java

There is only call by value in java, not call by reference. If we call a method passing a value, it is
known as call by value. The changes being done in the called method, is not affected in the calling
method.

Example of call by value in java

In case of call by value original value is not changed. Let's take a simple example:

Class Operation
{
Int data=50;

void change(int data)


{
data=data+100;//changes will be in the local variable only
}
public static void main(String args[])
{
Operation op=new Operation();
[Link]("before change "+[Link]);
[Link](500);
[Link]("after change "+[Link]);
}
}

Output:
before change 50
after change 50

In Java, parameters are always passed by value. For example, following program prints i = 10, j = 20.

// [Link] class
Test {
// swap() doesn't swap i and j

Example:

public static void swap(Integer i, Integer j)


{
Integer temp = new Integer(i);
i = j;
j = temp;
}
public static void main(String[] args)
{
Integer i = new Integer(10);
Integer j = new Integer(20);
JAVA PROGRAMMING Page 18
MRCET JAVA NOTES [Link] -I SEM-2024-2025

swap(i, j);
[Link]("i = " + i + ", j = " + j);
}
}

Access Control

Access Modifiers in java


There are two types of modifiers in java: access modifiers and non-access modifiers.
The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or
class.
There are 4 types of java access modifiers.
1. private

2. default
3. protected
4. public

Private access modifier


The private access modifier is accessible only within class.
Simple example of private access modifier
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class,
so there is compile time error

class A
{
private int data=40;
private void msg()
{
[Link]("Hello java");
}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A();
[Link]([Link]);//Compile Time Error
[Link]();//Compile Time Error
}
}

JAVA PROGRAMMING Page 19


MRCET JAVA NOTES [Link] -I SEM-2024-2025

2) default accessmodifier

If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible only
within package.
Example of default accessmodifier
In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.

//save by [Link] package pack;


class A
{
voidmsg()
{
[Link]("Hello");
}
}

//save by [Link] package mypack; import pack.*;


classB
{
public static void main(String args[])
{
A obj = new A();//Compile Time Error
[Link]();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be accessed
from outside the package.

3) protected accessmodifier

The protected access modifier is accessible within package and outside the package but through
inheritance only. The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.
Example of protected access modifier
In this example, we have created the two packages pack and mypack. The A class of pack package
is public, so can be accessed from outside the package. But msg method of this package is declared
as protected, so it can be accessed from outside the class only throughinheritance.
//save by [Link]
package pack;
public class A
{
protected void msg()
{
[Link]("Hello");
}

JAVA PROGRAMMING Page 20


MRCET JAVA NOTES [Link] -I SEM-2024-2025

}
//save by [Link]
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
[Link]();
}
}
Output:
Hello

4) Public access modifier

The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
Example of public access modifier
//save by [Link]
package pack;
public class A
{
public void msg()
{
[Link]("Hello");
}
}
//save by [Link]
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
[Link]();
}
}
Output:
Hello

Understanding all java access modifiers Let's understand the access modifiers by a simple table.

Access Within within Outside Outside


Modifier class package package by sub package
classonly
Private Y N N N
Default Y Y N N
Protected Y Y Y N

JAVA PROGRAMMING Page 21


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Public Y Y Y Y

this keyword in java


Usage of java this keyword
Here is given the 6 usage of java this keyword.
1. this can be used to refer current class instancevariable.

2. this can be used to invoke current class method(implicitly)

3. this() can be used to invoke current classconstructor.


4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructorcall.
6. this can be used to return the current class instance from themethod.

class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
[Link]=rollno;
[Link]=name;
[Link]=fee;
}
void display()
{
[Link](rollno+" "+name+" "+fee);
}
}
class TestThis2
{
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000f);
Student s2=newStudent(112,"sumit",6000f);
[Link]();
[Link]();
}
}
Output:
111 ankit 5000
112 sumit 6000

JAVA PROGRAMMING Page 22


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Difference between constructor and method in java

Java Constructor Java Method


Constructor is used to initialize the state of an Method is used to expose behaviour of an
object. object.

Constructor must not have return type. Method must have return type.
Constructor is invoked implicitly. Method is invoked explicitly.
The java compiler provides a default constructor Method is not provided by compiler in any case.
if you don't have any constructor
Constructor name must be same as the class Method name may or may not be same as class
name. name.

Constructor Overloading in Java

Constructor overloading is a technique in Java in which a class can have any number of constructors
that differ in parameter [Link] compiler differentiates these constructors by taking into account the
number of parameters in the list and their type.

Example of Constructor Overloading

class Student5
{
int id;
String name;
int age;
Student5(int i,String n)
{
id = i;
name = n;
}
Student5(int i,String n,int a)
{
id = i;
name = n;
age=a;
}
void display()
{
[Link](id+" "+name+" "+age);
}
public static void main(String args[])
{
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = newStudent5(222,"Aryan",25);
[Link]();
[Link]();
}
}

JAVA PROGRAMMING Page 23


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Output:
111 Karan 0
222 Aryan 25

Method Overloading in java


If a class has multiple methods having same name but different in parameters, it is known as
MethodOverloading.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
Method Overloading: changing no. of arguments
In this example, we have created two methods, first add() method performs addition of two numbers
and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for calling
methods.
classAdder
{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
classTestOverloading1
{
public static void main(String[] args)
{
[Link]([Link](11,11));
[Link]([Link](11,11,11));
}
}
Output:
22
33

JAVA PROGRAMMING Page 24


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Method Overloading: changing data type of arguments

In this example, we have created two methods that differs in data type. The first add method receives
two integer arguments and second add method receives two double arguments.

Java Garbage Collection

In java, garbage means unreferenced objects.


Garbage Collection is process of reclaiming the runtime unused memory automatically. In other
words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is performed
automatically. So, java provides better memory management.

Advantage of Garbage Collection

 It makes java memory efficient because garbage collector removes the unreferenced
objects from heapmemory.

 It is automatically done by the garbage collector(a part of JVM) so we don't need to make
extraefforts.

gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is
found in System and Runtime classes.
public static void gc()
{
}
Simple Example of garbage collection in java public class TestGarbage1
{
public void finalize()
{[Link]("object is garbage collected");
}
public static void main(String args[])
{
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null; [Link]();
}
}
object is garbage collected object is garbage collected

JAVA PROGRAMMING Page 25


MRCET JAVA NOTES [Link] -I SEM-2024-2025

MALLA REDDY COLLEGE OF ENGINEERING &TECHNOLOGY


DEPARTMENT OF EEE

Unit-2
Inheritance in Java

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of
parent object. Inheritance represents the IS-A relationship, also known as parent- childrelationship.
Why use inheritance in java
 For Method Overriding (so runtime polymorphism can beachieved).

 For CodeReusability.
Syntax of Java Inheritance
classSubclass-name extends Superclass-name 2.
{
//methods and fields4.
}
The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.

classEmployee
{
floatsalary=40000;
}
classProgrammer extends Employee
{
intbonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]);
}
}
Programmer salary is:40000.0
Bonus of programmeris:10000

JAVA PROGRAMMING Page 26


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Types of inheritance in java

Single Inheritance Example

File: [Link]
class Animal
{
voideat()
{
[Link]("eating...");}
}
classDog extends Animal
{
voidbark()
{
[Link]("barking...");
}
}
Class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
[Link]();
[Link]();
}
}
Output:
barking... eating...

JAVA PROGRAMMING Page 27


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Multilevel Inheritance Example


File: [Link]

classAnimal
{
voideat()
{
[Link]("eating...");
}
}
classDog extends Animal
{
voidbark(){[Link]("barking...");
}
}
classBabyDog extends Dog
{
voidweep()
{
[Link]("weeping...");
}
}
classTestInheritance2
{
public static void main(String args[])
{
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
}
}
Output:
weeping... barking... eating...

Member access and Inheritance

A subclass includes all of the members of its super class but it cannot access those members of
the super class that have been declared as private. Attempt to access a private variable would
cause compilation error as it causes access violation. The variables declared as private, is only
accessible by other members of its own class. Subclass have no access to it.

super keyword in java


The super keyword in java is a reference variable which is used to refer immediate parent class
object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly which
is referred by super reference variable.

JAVA PROGRAMMING Page 28


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Usage of java super Keyword

1. super can be used to refer immediate parent class instancevariable.

2. super can be used to invoke immediate parent classmethod.

3. super() can be used to invoke immediate parent classconstructor.

super is used to refer immediate parent class instance variable.


classAnimal
{
Stringcolor="white";
}
classDog extends Animal
{
Stringcolor="black";
voidprintColor()
{
[Link](color);//prints color of Dogclass
[Link]([Link]);//prints color of Animal class
}
}
classTestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
[Link]();
}
}
Output:
black
white

Final Keyword in Java

The final keyword in java is used to restrict the user. The java final keyword can be used in many
context. Final can be:
1. variable

2. method

3. class

The final keyword can be applied with the variables, a final variable that have no value it is called
blank final variable or uninitialized final variable. It can be initialized in the constructor only. The

JAVA PROGRAMMING Page 29


MRCET JAVA NOTES [Link] -I SEM-2024-2025

blank final variable can be static also which will be initialized in the static block only.
Polymorphism
Method Overriding in Java

If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in java.
Usage of Java Method Overriding
 Method overriding is used to provide specific implementation of a method that is already
provided by its superclass.

 Method overriding is used for runtimepolymorphism

Rules for Java Method Overriding


1. method must have same name as in the parentclass

2. method must have same parameter as in the parentclass.

3. must be IS-A relationship(inheritance).

/Java Program to illustrate the use of Java Method Overriding


//Creating a parent class.
class Vehicle
{
void run(){[Link]("Vehicle is running");
}
}
class Bike2 extends Vehicle
{
void run(){[Link]("Bike is running safely");
}

public static void main(String args[])


{
Bike2 obj = new Bike2();
[Link]();
}
}
Output:

Bike is running safely

Abstract class in Java

A class that is declared with abstract keyword is known as abstract class in java. It can have abstract
and non-abstract methods (method with body). It needs to be extended and its method implemented.
It cannot be instantiated.

JAVA PROGRAMMING Page 30


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Example abstract class


1. abstract classA{}
Abstract method
abstract void printStatus();//no body and abstract
abstract class Bike
{
abstract void run();
}
class Honda4 extends Bike
{
void run()
{
[Link]("running safely..");
}
public static void main(String args[])
{
Bike obj = new Honda4();
[Link]();
}
}
Output:
running safely..

Interfaces

Interface in Java
An interface in java is a blueprint of a class. It has static constants and abstract methods.
The interface in java is a mechanism to achieve abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve abstraction and multiple
inheritance in Java.
Java Interface also represents IS-A relationship. It cannot be instantiated just like abstract class.
There are mainly three reasons to use interface. They are given below.
 It is used to achieveabstraction.
 By interface, we can support the functionality of multipleinheritance.
 It can be used to achieve loosecoupling.

JAVA PROGRAMMING Page 31


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Interfaces Vs Abstract classes


Abstract class Interface
1) Abstract class can have abstract and Interface can have only abstract methods. Since Java 8,
non-abstract methods. it can have default and static methods also.
2) Abstract class doesn't support Interface supports multiple inheritance.
multiple inheritance.
3) Abstract class can have final, non- Interface has only static and final variables.
final, static and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation of abstract
implementation ofinterface. class.
5) The abstract keyword is used to The interface key is used to declare
declare abstract class. interface
6) Example: Example:
Public abstract class Shape { public Public interface Drawable { void Draw()}
abstract void Draw()}

Example:
interface printable
{
void print();
}
class A6 implements printable
{
public void print()
{
[Link]("Hello");
}
public static void main(String args[])
{
A6 obj = new A6();
[Link]();
}
}

Output: hello

Java Package

A java package is a group of similar types of classes, interfaces and sub-packages. Package in
java can be categorized in two form, built-in package and user-defined package. There are many
built-in packages such as java, lang, awt, javax, swing, net, io, util, sql [Link] of
JavaPackage
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides accessprotection.
3) Java package removes namingcollision

JAVA PROGRAMMING Page 32


MRCET JAVA NOTES [Link] -I SEM-2024-2025

package mypack;
public class Simple
{
public static void main(String args[])
{
[Link]("Welcome to package");
}
}

How to compile java package


If you are not using any IDE, you need to follow the syntax given below: javac -d directory
javafilename
How to run java package program
To Compile: javac -d . [Link]
To Run: java [Link]
Using fully qualified name
Example of package by import fully qualified name
//save by [Link]
package pack;
public class A
{
public void msg()
{
[Link]("Hello");
}
}

JAVA PROGRAMMING Page 33


MRCET JAVA NOTES [Link] -I SEM-2024-2025

//save by [Link]
package mypack;
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A();//using fully qualified name [Link]();
}
}
Output:Hello

JAVA PROGRAMMING Page 34


MRCET JAVA NOTES [Link] -I SEM-2024-2025

MALLA REDDY COLLEGE OF ENGINEERING &TECHNOLOGY


DEPARTMENT OF EEE

UNIT-3
Exception Handling

The exception handling in java is one of the powerful mechanism to handle the runtime errors so that
normal flow of the application can bemaintained.

What is exception
In java, exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.

Advantage of Exception Handling


The core advantage of exception handling is to maintain the normal flow of the application. Exception
normally disrupts the normal flow of the application that is why we use exception handling.

Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun microsystem says there are three types of exceptions:
1. CheckedException

2. UncheckedException

3. Error

Difference between checked and unchecked exceptions


1) Checked Exception: The classes that extend Throwable class except RuntimeException and Error
are known as checked exceptions [Link], SQLException etc. Checked exceptions are
checked atcompile-time.

2) Unchecked Exception: The classes that extend RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are checked atruntime.

3) Error: Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionErroretc.

JAVA PROGRAMMING Page 35


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Hierarchy of Java Exception classes

Checked and UnChecked Exceptions

JAVA PROGRAMMING Page 36


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Java try block


Java try block is used to enclose the code that might throw an exception. It must be used within the
method.
Java try block must be followed by either catch or finally block.
Syntax of java try-catch
1. try{
2. //code that may throwexception
3. }catch(Exception_class_Name ref){}Syntax of try-finallyblock
1. try{
2. //code that may throwexception
3. }finally{}

Java catch block


Java catch block is used to handle the Exception. It must be used after the try block only. You can
use multiple catch block with a single try.
Problem without exception handling
Let's try to understand the problem if we don't use try-catch block.
public class Testtrycatch1
{
public static void main(String args[])
{
int data=50/0;//may throw exception
[Link]("rest of thecode...");
}
}
Output:
Exception in thread main [Link]:/ byzero

As displayed in the above example, rest of the code is not executed (in such case, rest of the code...
statement is not printed).

There can be 100 lines of code after exception. So all the code after exception will not be
executed.
Solution by exception handling Let's see the solution of above problem by java try-catch block.

JAVA PROGRAMMING Page 37


MRCET JAVA NOTES [Link] -I SEM-2024-2025

public class Testtrycatch2


{
public static void main(String args[])
{
try
{
intdata=50/0;
}
catch(ArithmeticException e)
{
[Link](e);
}
[Link]("rest of the code...");
}
}
1. Output:
Exception in thread main [Link]:/ by zero rest of the code...
Multithreading

Differences between multi-threading and multitasking,

JAVA PROGRAMMING Page 38


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Multithreading in java is a process of executing multiple threads simultaneously.


Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking. But we use multithreading than
multiprocessing because threads share a common memory area. They don't allocate separate
memory area so saves memory, and context-switching between the threads takes less time than
process. Java Multithreading is mostly used in games, animation etc.

Advantages of Java Multithreading


1) It doesn't block the user because threads are independent and you can perform multiple
operations at sametime.
2) You can perform many operations together so it savestime.
3) Threads are independent so it doesn't affect other threads if exception occur in a singlethread.

Life cycle of a Thread (Thread States)


A thread can be in one of the five states. According to sun, there is only 4 states in thread life
cycle in java new, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:

1. New
2. Runnable
3. Running
4. Non-Runnable(Blocked)
5. Terminated

JAVA PROGRAMMING Page 39


MRCET JAVA NOTES [Link] -I SEM-2024-2025

How to create thread


There are two ways to create a thread:

1. By extending Threadclass
2. By implementing Runnableinterface.

Thread class:
Thread class provide constructors and methods to create and perform operations on a
[Link] class extends Object class and implements Runnable interface.

JAVA PROGRAMMING Page 40


MRCET JAVA NOTES [Link] -I SEM-2024-2025

MALLA REDDY COLLEGE OF ENGINEERING &TECHNOLOGY


DEPARTMENT OF EEE

UNIT 4
APPLETS

Applets – Concepts of Applets, differences between applets and applications, life cycle of an applet,
types of applets, creating applets, passing parameters to applets.
Event Handling- Events, Event sources, Event classes, Event Listeners, Delegation event model,
handling mouse and keyboard events, Adapter classes. Streams- Byte streams, Character streams,
Text input/output.
APPLETS:
An applet is a program that comes from server into a client and gets executed at client side and
displays the result.
An applet represents byte code embedded in a html page. (Applet = bytecode + html) and run
with the help of Java enabled browsers such as Internet Explorer.
An applet is a Java program that runs in a browser. Unlike Java applications applets do not have
a main () method.
To create applet we can use [Link] or [Link] class. All applets inherit the
super class „Applet‟. An Applet class contains several methods that help to control the execution
of an applet.
Advantages:
 Applets provide dynamic nature for a webpage.
 Applets are used in developing games and animations.
 Writing and displaying (browser) graphics and animations is easier than
 applications.
 In GUI development, constructor, size of frame, window closing code etc. are not required

Restrictions of Applets of Applets Vs Applications


 Applets are required separate compilation before opening in a browser.
 In realtime environment, the bytecode of applet is to be downloaded from the server to the
client machine.
 Applets are treated as untrusted (as they were developed by unknown people and placed on
 unknown servers whose trustworthiness is not guaranteed).
 Extra Code is required to communicate between applets using AppletContext.

JAVA PROGRAMMING Page 41


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Differences between applets and applications,

LIFE CYCLE OF AN APPLET


Let the Applet class extends Applet or JApplet class.

JAVA PROGRAMMING Page 42


MRCET JAVA NOTES [Link] -I SEM-2024-2025

public void init(): This method is used for initializing variables, parameters to create
components. This method is executed only once at the time of applet loaded into memory.
public void init()
{
//initialization
}

Runnning:

public void start (): After init() method is executed, the start method is executed automatically.
Start method is executed as long as applet gains focus. In this method code related to opening
files and connecting to database and retrieving the data and processing
the data is written.
Idle / Runnable:
public void stop (): This method is executed when the applet loses focus. Code related to closing
the files and database, stopping threads and performing clean up operations are written in this stop
method.
Dead/Destroyed:
public void destroy (): This method is executed only once when the applet is terminated
from the memory.
Executing above methods in that sequence is called applet life cycle.
We can also use public void paint (Graphics g) in applets.
//An Applet skeleton.

import [Link].*;
import [Link].*;
/*
<applet code="AppletSkel" width=300 height=100>
</applet>
*/
public class AppletSkel extends Applet
{
3 Called first.
public void init()
{
4 initialization
}
/* Called second, after init(). Also called whenever the applet is restarted. */
public void start()
{
3 start or resume execution
}
4 Called when the applet is
stopped. public void stop()
{
5 suspends execution

JAVA PROGRAMMING Page 43


MRCET JAVA NOTES [Link] -I SEM-2024-2025

/* Called when applet is terminated. This is the last method executed. */


public void destroy()
{
5 perform shutdown activities
}
6 Called when an applet's window must be
restored. public void paint(Graphics g)
{
7 redisplay contents of window
}
}

After writing an applet, an applet is compiled in the same way as Java application but running of
an applet is different.

There are two ways to run an applet.


 Executing an applet within a Java compatible web browser.
 Executing an applet using „appletviewer‟. This executes the applet in a window.

To execute an applet using web browser, we must write a small HTML file which contains the
appropriate „APPLET‟ tag. <APPLET> tag is useful to embed an applet into an HTML page. It
has the following form:

<APPLET CODE=”name of the applet class file” HEIGHT = maximum height of applet in pixels
WIDTH = maximum width of applet in pixels ALIGN = alignment (LEFT, RIGHT, MIDDLE, TOP,
BOTTOM)>
<PARAM NAME = parameter name VALUE = its value> </APPLET>

Execution: appletviewer [Link] or appletviewer [Link]


The <PARAM> tag useful to define a variable (parameter) and its value inside the HTML page
which can be passed to the applet. The applet can access the parameter value using getParameter
() method, as: String value = getParameter (“pname”);
Example Program:
Following is a simple applet named [Link] −
import [Link].*;
import [Link].*;
public class HelloWorldApplet extends Applet
{
public void paint (Graphics g)
{
[Link] ("Hello World", 25, 50);
}
}
Create an HTML file in notpad
<html>
<title>The Hello, World Applet</title>
<applet code = "[Link]" width = "320" height = "120">
</applet>
JAVA PROGRAMMING Page 44
MRCET JAVA NOTES [Link] -I SEM-2024-2025

</html>

OUTPUT: javac [Link]


appletviewer [Link]

TYPES OF APPLETS
Applets are of two types:
// Local Applets
// Remote Applets
Local Applets: An applet developed locally and stored in a local system is called local applets.
So, local system does not require internet. We can write our own applets and embed them into the
web pages.
Remote Applets: The applet that is downloaded from a remote computer system and embed applet
into a web page. The internet should be present in the system to download the applet and run it.
To download the applet we must know the applet address on web known as Uniform Resource
Locator(URL) and must be specified in the applets HTML document as the value of
CODEBASE

Local Applets

Remote Applets

PASSING PARAMETERS TO AN APPLET

Java applet has the feature of retrieving the parameter values passed from the html page. So, you
can pass the parameters from your html page to the applet embedded in your page. The param

JAVA PROGRAMMING Page 45


MRCET JAVA NOTES [Link] -I SEM-2024-2025

tag(<parma name="" value=""></param>) is used to pass the parameters to an applet. The


applet has to call the getParameter() method supplied by the [Link] parent class.

import [Link].*;
/* <applet code="[Link]" width = 600 height= 450>
<param name = "t1" value="Hari Prasad"> <param name =
"t2" value ="101">
</applet> */
public class MyApplet2 extends Applet
{
String n;
String id;
public void init()
{
n = getParameter("t1");
id = getParameter("t2");
}
public void paint(Graphics g)
{
rawString("Name is : "
+ n, 100,100);
[Link]("Id is :
"+ id, 100,150);
}
}
Ouput

EVENT HANDLING

Event handling is at the core of successful applet programming. Most events to which the applet
will respond are generated by the user. The most commonly handled events are those generated
by the mouse, the keyboard, and various controls, such as a push button.
Events are supported by the [Link] package.

JAVA PROGRAMMING Page 46


MRCET JAVA NOTES [Link] -I SEM-2024-2025

The Delegation Event Model

The modern approach to handling events is based on the delegation event model, which
defines standard and consistent mechanisms to generate and process events.

Its concept is quite simple: a source generates an event and sends it to one or more
listeners. In this scheme, the listener simply waits until it receives an event. Once received,
the listener processes the event and then returns.

The advantage of this design is that the application logic that processes events is
cleanly separated from the user interface logic that generates those events. A user interface
element is able to "delegate" the processing of an event to a separate piece of code.
In the delegation event model, listeners must register with a source in order to
receive an event notification. This provides an important benefit: notifications are sent only
to listeners that want to receive them.

EVENTS
In the delegation model, an event is an object that describes a state change in a source. It can be
generated as a consequence of a person interacting with the elements in a graphical user interface.
Some of the activities that cause events to be generated are pressing a button, entering a character
via the keyboard, selecting an item in a list, and clicking the mouse.
Events may also occur that are not directly caused by interactions with a user interface.

For example, an event may be generated when a timer expires, a counter exceeds a value, software
or hardware failure occurs, or an operation is completed.

EVENT SOURCES
A source is an object that generates an event. This occurs when the internal state of that object
changes in some way. Sources may generate more than one type of event. A source must register
listeners in order for the listeners to receive notifications about a specific type of event. Each type
of event has its own registration method.
Here is the general form:
public void add Type Listener( Type Listener el )

EVENT LISTENERS
A listener is an object that is notified when an event occurs. It has two major requirements. First,

JAVA PROGRAMMING Page 47


MRCET JAVA NOTES [Link] -I SEM-2024-2025

it must have been registered with one or more sources to receive notifications about specific types
of events. Second, it must implement methods to receive and process these notifications. The
methods that receive and process events are defined in a set of interfaces found in
[Link].

For example, the MouseMotionListener interface defines two methods to receive notifications
when the mouse is dragged or moved.
EVENT CLASSES
The classes that represent events are at the core of Java's event handling mechanism. At the root
of the Java event class hierarchy is EventObject, which is in [Link]. It is the superclass for all
events.
It’s one constructor is shown here:
EventObject(Object src )
EventObject contains two methods: getSource( ) and toString( ) .
The getSource( ) method returns the source of the event. Ex: Object getSource( )
toString( ) returns the string equivalent of the event.
The MouseEvent Class

There are eight types of mouse events. The MouseEvent class defines the following integer
constants that can be used to identify them:
MOUSE_CLICKED The user clicked the mouse.
MOUSE_DRAGGED The user dragged the mouse.
MOUSE_ENTERED The mouse entered a component.
MOUSE_EXITED The mouse exited from a component.
MOUSE_MOVED The mouse moved.
MOUSE_PRESSED The mouse was pressed.
MOUSE_RELEASED The mouse was released.
MOUSE_WHEEL The mouse wheel was moved (Java 2, v1.4).
EX: // Demonstrate the mouse event handlers.
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/
public class MouseEvents extends Applet implements MouseListener, MouseMotionListener
{
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init() {
addMouseListener(this);
addMouseMotionListener(this);
}
// Handle mouse clicked.

JAVA PROGRAMMING Page 48


MRCET JAVA NOTES [Link] -I SEM-2024-2025

public void mouseClicked(MouseEvent me)


{
mouseX = 0; // save coordinates
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
// Handle mouse entered.
public void mouseEntered(MouseEvent me)
{
// save
coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent me)
{
// save
coordinate
s mouseX
= 0;
mouseY =
10;
msg = "Mouse exited.";
repaint();
}
// Handle button pressed.
public void mousePressed(MouseEvent me)
{
// save coordinates
mouseX =
[Link]();
mouseY =
[Link](); msg =
"Down"; repaint();
}
// Handle button released.
public void mouseReleased(MouseEvent me)
{
1. save
coordinates
mouseX =
[Link]();
mouseY =
[Link](); msg
= "Up";
repaint();
}
2. Handle mouse dragged.
public void mouseDragged(MouseEvent me)

JAVA PROGRAMMING Page 49


MRCET JAVA NOTES [Link] -I SEM-2024-2025

{
1. save coordinates
mouseX =
[Link]();
mouseY = [Link]();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}

// Handle mouse moved.


public void mouseMoved(MouseEvent me)
{
// show status
showStatus("Moving mouse at " + [Link]() + ", " + [Link]());
}
// Display msg in applet window at current X,Y location.
public void paint(Graphics g)
{
[Link](msg, mouseX, mouseY);
}
}

keyboard event class


Handling Keyboard Events
When a key is pressed, a KEY_PRESSED event is generated. This results in a call to the
keyPressed( ) event handler. When the key is released, a KEY_RELEASED event is generated
and the keyReleased( ) handler is executed. If a character is generated by the keystroke, then a
KEY_TYPED event is sent and the keyTyped( ) handler is invoked.
Thus, each time the user presses a key, at least two and often three events are generated. If all you
care about are actual characters, then you can ignore the information passed by the key press and
JAVA PROGRAMMING Page 50
MRCET JAVA NOTES [Link] -I SEM-2024-2025

release events.
KEY_PRESSED
KEY_TYPED (is only generated if a valid Unicode character could be generated.)
KEY_RELEASED

EX: // Demonstrate the key event handlers.


import [Link].*;
import [Link].*;
import [Link].*;

/* <applet code="SimpleKey" width=300


height=100> </applet> */

public class SimpleKey extends Applet implements KeyListener


{
String msg = "";
int X = 10, Y = 20; // output coordinates
public void init()
{
addKeyListener(this);
requestFocus(); // request input focus
}
public void keyPressed(KeyEvent ke)
{
showStatus("Key Down");
}
public void keyReleased(KeyEvent ke)
{
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke)
{
msg += [Link]();
repaint();
}
// Display keystrokes.
public void paint(Graphics g)
{
[Link](msg, X, Y);
}
}

JAVA PROGRAMMING Page 51


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Files and Streams:


Text stream classes for reading data Text stream classes for writing data

Stream
A stream can be defined as a sequence of data. There are two kinds of Streams −
 InPutStream − The InputStream is used to read data from a source.
 OutPutStream − The OutputStream is used for writing data to a destination.
Java provides strong but flexible support for I/O related to files and networks.

Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are
many
classes related to byte streams but the most frequently used classes are, FileInputStream and

File Output Stream.


Example
import [Link].*;
public class CopyFile
{
public static void main(String args[]) throws IOException
{
FileInputStream in = null;
FileOutputStream out = null;
try
{
in = new FileInputStream("[Link]");
out = new FileOutputStream("[Link]");
int c;

JAVA PROGRAMMING Page 52


MRCET JAVA NOTES [Link] -I SEM-2024-2025

while ((c = [Link]()) != -1)


{
[Link](c);
}
}finally
{
if (in != null)
{
[Link]();
}
if (out != null)
{
[Link]();
}
}
}
}
Now let's have a file [Link] with the following content:
This is test for copy file.
$javac [Link]
$java CopyFile

Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas
Java Character streams are used to perform input and output for 16-bit unicode. Though
there are many classes related to character streams but the most frequently used classes
are, FileReader and FileWriter.
Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but
here the major difference is that FileReader reads two bytes at a time and FileWriter writes two
bytes at a time.

Example
import [Link].*;
public class CopyFile
{
public static void main(String args[]) throws IOException
{
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("[Link]");
out = new FileWriter("[Link]");
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
}finally {
if (in != null) {
[Link]();

JAVA PROGRAMMING Page 53


MRCET JAVA NOTES [Link] -I SEM-2024-2025

}
if (out != null) {
[Link]();
}
}
}
}

Reading and Writing Files Text input/output,


As described earlier, a stream can be defined as a sequence of data. The InputStream is used
to
read data from a source and the OutputStream is used for writing data to a destination. Here is
a hierarchy of classes to deal with Input and Output streams.

The two important streams are FileInputStream and FileOutputStream (File Handling)
In Java, FileInputStream and FileOutputStream classes are used to read and write data in file. In
another words, they are used for file handling in java.
Java FileOutputStream class
Java FileOutputStream is an output stream for writing data to a file. It is a class belongs to byte
streams. It can be used to create text files.

First we should read data from the keyword. It uses DataInputStream class for reading data from
the
keyboard is as:
DataInputStream dis=new DataInputStream([Link]);

FileOutputStream used to send data to the file and attaching the file to FileOutputStream.
i.e.,
FileOutputStream fout=new FileOutputStream(“File_name”);

JAVA PROGRAMMING Page 54


MRCET JAVA NOTES [Link] -I SEM-2024-2025

The next step is to read data from DataInputStream and write it into FileOutputStream. It means
read data
from dis object and write it into fout object. i.e.,
ch=(char)[Link](); //read one character into ch
[Link](ch); //write ch into file.

Finally closing the file using: [Link]();


Creating a Text file:

Example: Write a program to read data from the keyboard and write it to [Link] file.
import [Link].*;
class Test
{
public static void main(String args[])
{
DataInputStream dis=new DataInputStream([Link]);
FileOutputstream fout=new
FileOutputStream("[Link]"); [Link]("Enter
text @ at the end:”); char ch;
while((ch=(char)[Link]())!=‟@‟)
[Link](ch);
[Link]();
}
}
Output: javac [Link]
Java Test

Java FileInputStream class


It is useful to read data from a file in the form of sequence of bytes. It is possible to read data
from a text file using FileInputStream. i.e.,
FileInputStream fin= new FileInputStream(“[Link]”);

To read data from


the file is, ch=[Link]();

JAVA PROGRAMMING Page 55


MRCET JAVA NOTES [Link] -I SEM-2024-2025

When there is no more data available to read then it returns -1.

The Output Stream is used to send data to the monitor. i.e., PrintStream, for displaying the data we
can use [Link].
[Link](ch);

Reading data from a text file using FileInputStream:


Java FileInputStream class obtains input bytes from a file. It is used for reading streams of raw
bytes such as image data. It should be used to read byte-oriented data for example to read image,
audio, video etc

Example: Write a program to read data from [Link] using FileInputStream and display
it on monitor.
import [Link].*;
class ReadFile
{
public static void main(String args[])
{
FileInputStream fin=new FileInputStream("[Link]");
[Link](“File Contents:”); int ch;
while((ch=[Link]())!=-1)
{
[Link]((char)ch);
}
[Link]();
}
}
Output: javac [Link]
java ReadFile

JAVA PROGRAMMING Page 56


MRCET JAVA NOTES [Link] -I SEM-2024-2025

MALLA REDDY COLLEGE OF ENGINEERING &TECHNOLOGY


DEPARTMENT OF EEE

UNIT V
GUI Programming with Java

GUI Programming with Java – AWT class hierarchy, component, container,


panel, window, frame, graphics.

AWT controls: Labels, button, text field, check box, check box groups, choices, lists,
scrollbars, and graphics.

Layout Manager – Layout manager types: border, grid and flow.

Swing – Introduction, limitations of AWT, Swing vs AWT.


GUI PROGRAMMING WITH JAVA
ABSTRACT WINDOW TOOLKIT (AWT)

Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based application
in java. Java AWT components are platform-dependent i.e. components are displayed according
to the view of operating system. AWT is heavyweight i.e. its components uses the resources of
system. The Abstract Window Toolkit(AWT) support for applets. The AWT contains numerous
classes and methods that allow you to create and manage windows.
The [Link] package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
AWT Classes
The AWT classes are contained in the [Link] package. It is one of Java's largest packages.
Control Fundamentals

The AWT supports the following types of controls:


3. Labels
4. Push buttons
5. Check boxes
6. Choice lists
7. Lists
8. Scroll bars
9. Text editing
User interaction with the program is of two types:
CUI (Character User Interface): In CUI user interacts with the application by
typing characters or commands. In CUI user should remember the commands. It is not user friendly.

JAVA PROGRAMMING Page 57


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Class Description
AWTAWTEvent Encapsulates AWT events.
AWTEventMulticaster Dispatches events to multiple listeners.
BorderLayout Border layouts use five components: North, South, East, West, and
Center.
CardLayout Card layouts emulate index cards. Only the one on top is showing.
Checkbox Creates a check box control.
CheckboxGroup Creates a group of check box controls.
CheckboxMenuItem Creates an on/off menu item.
Choice Creates a pop-up list.

Color Manages colors in a portable, platform-independent fashion.


Component An abstract superclass for various AWT components.
Container A subclass of Component that can hold other components.
Cursor Encapsulates a bitmapped cursor.
Dialog Creates a dialog window.
Dimension Specifies the dimensions of an object. The width is stored in
width , and the height is stored in height .

Event Encapsulates events.


FlowLayout The flow layout manager. Flow layout positions components left
to right, top to bottom.

Frame Creates a standard window that has a title bar, resize corners, and
a menu bar.

Graphics Encapsulates the graphics context.

2. GUI (Graphical User Interface): In GUI user interacts with the application through graphics.
GUI is user friendly. GUI makes application attractive. It is possible to simulate real object in
GUI programs. In java to write GUI programs we can use awt (Abstract Window Toolkit)
package.

JAVA PROGRAMMING Page 58


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Java AWT Class Hierarchy


The hierarchy of Java AWT classes is given below.

Container

The Container is a component in AWT that can contain other components like buttons, textfields,
labels etc. The classes that extend Container class are known as container such as Frame, Dialog
and Panel.
Window
The window is the container that has 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.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.

JAVA PROGRAMMING Page 59


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Listeners and Listener Methods:


Listeners are available for components. A Listener is an interface that listens to an event from a
component. Listeners are available in [Link] package. The methods in the listener interface
are to be implemented, when using that listener.

JAVA PROGRAMMING Page 60


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Layout Managers
A layout manager arranges the child components of a container. It positions and sets the size of
components within the container's display area according to a particular layout scheme.
The layout manager's job is to fit the components into the available area, while maintaining the
proper spatial relationships between the components. AWT comes with a few standard layout
managers that will collectively handle most situations; you can make your own layout managers
if you have special requirements

The following applet adds five buttons to the default FlowLayout.


import [Link].*;
/*
<applet code="Flow" width="500" height="500">
</applet>
*/
public class Flow extends [Link]
{
public void init()
{
//Default for Applet is FlowLayout
add( new Button("One") );
add( new Button("Two") );
add( new Button("Three") );
add( new Button("Four") );
add( new Button("Five") );
}
}

If the applet is small enough, some of the buttons spill over to a second or third row.
Grid Layout
GridLayout arranges components into regularly spaced rows and columns. The components
are arbitrarily resized to fit in the resulting areas; their minimum and preferred sizes are
consequently ignored.
GridLayout is most useful for arranging very regular, identically sized objects and for
allocating space for Panels to hold other layouts in each region of the container.
GridLayout takes the number of rows and columns in its constructor. If you subsequently give
it too many objects to manage, it adds extra columns to make the objects fit. You can also set the
number of rows or columns to zero, which means that you don't care how many elements the layout
manager packs in that dimension.

JAVA PROGRAMMING Page 61


MRCET JAVA NOTES [Link] -I SEM-2024-2025

For example, GridLayout(2,0) requests a layout with two rows and an unlimited number of
columns; if you put ten components into this layout, you'll get two rows of five columns each. The
following applet sets a GridLayout with three rows and two columns as its layout manager;
import [Link].*;
/*
<applet code="Grid" width="500"
height="500"> </applet>
*/
public class Grid extends [Link]
{
public void init()
{
setLayout( new GridLayout( 3, 2 ));
add( new Button("One") );
add( new Button("Two") );
add( new Button("Three") );
add( new Button("Four") );
add( new Button("Five") );
}
}

The five buttons are laid out, in order, from left to right, top to bottom, with one empty spot.
Border Layout

BorderLayout is a little more interesting. It tries to arrange objects in one of five geographical

locations: "North," "South," "East," "West," and "Center," possibly with some padding between.

BorderLayout is the default layout for Window and Frame objects. Because each component

is associated with a direction, BorderLayout can manage at most five components; it squashes or
stretches those components to fit its constraints.

When we add a component to a border layout, we need to specify both the component and the
position at which to add it. To do so, we use an overloaded version of the add() method that takes
an additional argument as a constraint.
The following applet sets a BorderLayout layout and adds our five buttons again, named for their
locations;

JAVA PROGRAMMING Page 62


MRCET JAVA NOTES [Link] -I SEM-2024-2025

import [Link].*;
/*
<applet code="Border" width="500" height="500">
</applet>
*/
public class Border extends [Link]
{
public void init()
{
setLayout( new [Link]() );
add( new Button("North"), "North" );
add(new Button("East"), "East" );
add( new Button("South"), "South" );
add( new Button("West"), "West" );
add( new Button("Center"), "Center" );
}
}
Compile: javac [Link]
Run : appletviewer [Link]
Java AWT Example
To create simple awt example, you need a frame. There are two ways to create a frame in AWT.
// By extending Frame class (inheritance)
2. By creating the object of Frame class (association)

Simple example of AWT by inheritance

import [Link].*;
class First extends Frame
{
First()
{
Button b=new Button("click me");
[Link](30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300
height setLayout(null);//no layout manager
setVisible(true);//now frame will be visible
}
public static void main(String args[])
{
First f=new First();
}
}

JAVA PROGRAMMING Page 63


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Simple example of AWT by association


import [Link].*;
class First2
{
First2()
{
Frame f=new Frame();
Button b=new Button("click me");
[Link](30,50,80,30);
[Link](b);
[Link](300,300);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
First2 f=new First2();
}
}
AWT controls
Labels:
The easiest control to use is a label. A label is an object of type Label, and it contains a string,
which it displays. Labels are passive controls that do not support any interaction with the user.
// Demonstrate
Labels import
[Link].*; import
[Link].*; /*
<applet code="LabelDemo" width=300 height=200>
</applet> */
public class LabelDemo extends Applet
{
public void init()
{
Label Label("One");
Label two = new Label("Two");
Label three = new Label("Three");
add labels to applet window
add(one);
add(two);
add(three);
}
}

JAVA PROGRAMMING Page 64


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Buttons:
The most widely used control is the push button. A push button is a component that contains a label
and that generates an event when it is pressed. Push buttons are objects of type Button. Button class is
useful to create push buttons. A push button triggers a series of events.
To create push button: Button b1 =new Button("label");
To get the label of the button: String l = [Link]();
To set the label of the button: [Link]("label");
To get the label of the button clicked: String str = [Link]();


\{ Demonstrate Buttons

import [Link].*;
import [Link].*;
import [Link].*;
/* <applet code="ButtonDemo" width=250 height=150>
</applet> */
public class ButtonDemo extends Applet implements ActionListener
{
String msg = "";
Button yes, no, maybe;
public void init()
{
yes = new Button("Yes");
no = new Button("No");
maybe = new Button("Undecided");
add(yes);
add(no);
add(maybe);
[Link](this);
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent ae)
{
String str = [Link]();
if([Link]("Yes"))
{
msg = "You pressed Yes.";
}
else if([Link]("No"))
{
msg = "You pressed No.";
}
else

JAVA PROGRAMMING Page 65


MRCET JAVA NOTES [Link] -I SEM-2024-2025

{
msg = "You pressed Undecided.";
}
repaint();
}
public void paint(Graphics g)
{
[Link](msg, 6, 100);
}
}
Check Boxes:
A check box is a control that is used to turn an option on or off. It consists of a small box that
can either contain a check mark or not. There is a label associated with each check box that
describes what option the box represents. You change the state of a check box by clicking on
it. Check boxes can be used individually or as part of a group.
\{ Demonstrate check boxes.
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="CheckboxDemo" width=250 height=200>
</applet>
*/
public class CheckboxDemo extends Applet implements ItemListener
{
String msg = "";
checkbox Win98, winNT, solaris, mac;
public void init()
{
win98 = new Checkbox("Windows 98/XP", null, true);
winNT = new Checkbox("Windows NT/2000");
solaris = new Checkbox("Solaris"); mac = new
Checkbox("MacOS");
add(Win98);
add(winNT);
add(solaris);
add(mac);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}

JAVA PROGRAMMING Page 66


MRCET JAVA NOTES [Link] -I SEM-2024-2025

// Display current state of the check boxes.


public void paint(Graphics g)
{
msg = "Current state: ";
[Link](msg, 6, 80);
msg = " Windows 98/XP: " + [Link]();
[Link](msg, 6, 100);
msg = " Windows NT/2000: " + [Link]();
[Link](msg, 6, 120);
msg = " Solaris: " + [Link]();
[Link](msg, 6, 140);
msg = " MacOS: " + [Link]();
[Link](msg, 6, 160);
}
}
TextField:
The TextField class implements a single-line text-entry area, usually called an edit control. Text
fields allow the user to enter strings and to edit the text using the arrow keys, cut and paste keys,
and mouse selections.

// Demonstrate text field.

import [Link].*;
import
[Link].*;
import [Link].*;
/*
<applet code="TextFieldDemo" width=380 height=150>
</applet>
*/
public class TextFieldDemo extends Applet implements ActionListener
{
TextField name, pass;
public void init()
{
Label namep = new Label("Name: ", [Link]);
Label passp = new Label("Password: ", [Link]);
name = new TextField(12);
pass = new TextField(8);
[Link]('?');
add(namep);
add(name);
add(passp);
add(pass);
// register to receive action events
[Link](this);
JAVA PROGRAMMING Page 67
MRCET JAVA NOTES [Link] -I SEM-2024-2025

[Link](this);
}

// User pressed Enter.


public void actionPerformed(ActionEvent ae)
{
repaint();
}
public void paint(Graphics g)
{
[Link]("Name: " + [Link](), 6, 60);
[Link]("Selected text in name: " + [Link](), 6, 80);
[Link]("Password: " + [Link](), 6, 100);
}
}
TextArea:
Sometimes a single line of text input is not enough for a given task. To handle these
situations, the AWT includes a simple multiline editor called TextArea .

\{ Demonstrate

TextArea. import
[Link].*; import
[Link].*;
/*
<applet code="TextAreaDemo" width=300
height=250> </applet>
*/
public class TextAreaDemo extends Applet
{
public void init()
{
String val = "There are two ways of constructing " + "a software design.\n" + "One way is to make
it so simple\n" + "that there are obviously no deficiencies.\n" + "And the other way is to make it
so complicated\n" + "that there are no obvious deficiencies.\n\n" + " -C.A.R. Hoare\n\n"
+ "There's an old story about the person who wished\n" + "his computer were as easy to use as his
telephone.\n" + "That wish has come true,\n" + "since I no longer know how to use my
telephone.\n\n" + " -Bjarne Stroustrup, AT&T, (inventor of C++)";
TextArea text = new TextArea(val, 10, 30);
add(text);
}
}

JAVA PROGRAMMING Page 68


MRCET JAVA NOTES [Link] -I SEM-2024-2025

CheckboxGroup

It is possible to create a set of mutually exclusive check boxes in which one and only one check
box in the group can be checked at any one time. These check boxes are often called radio
buttons. A Radio button represents a round shaped button such that only one can be selected
from a panel. Radio button can be created using CheckboxGroup class and Checkbox classes.
· To create a radio button: CheckboxGroup cbg = new CheckboxGroup ();
Checkbox cb = new Checkbox ("label", cbg, true);
· To know the selected checkbox: Checkbox cb = [Link] ();
·To know the selected checkbox label: String label = [Link]().getLabel ();

\{ Demonstrate check box group.

import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="CBGroup" width=250 height=200>
</applet>
*/
public class CBGroup extends Applet implements ItemListener
{
String msg = "";
Checkbox Win98, winNT, solaris, mac;
CheckboxGroup cbg;
public void init()
{
cbg = new CheckboxGroup();
Win98 = new Checkbox("Windows 98/XP", cbg, true);
winNT = new Checkbox("Windows NT/2000", cbg, false);
solaris = new Checkbox("Solaris", cbg, false); mac = new
Checkbox("MacOS", cbg, false);
add(Win98);
add(winNT);
add(solaris);
add(mac);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}

JAVA PROGRAMMING Page 69


MRCET JAVA NOTES [Link] -I SEM-2024-2025

\{ Display current state of the check


boxes. public void paint(Graphics g) {
msg = "Current selection: ";
msg += [Link]().getLabel();
[Link](msg, 6, 100);
}
}
Choice Controls
The Choice class is used to create a pop-up list of items from which the user may choose.
Thus, a Choice control is a form of menu. Choice menu is a popdown list of items. Only
one item can be selected.
· To create a choice menu: Choice ch = new Choice();
· To add items to the choice menu: [Link] ("text");
· To know the name of the item selected from the choice menu:
String s = [Link] ();
· To know the index of the currently selected item: int i = [Link]();
This method returns -1, if nothing is selected.
//Demonstrate Choice
lists. import
[Link].*; import
[Link].*;
import [Link].*;
/*
<applet code="ChoiceDemo" width=300
height=180> </applet>
*/
public class ChoiceDemo extends Applet implements ItemListener
{
Choice os, browser;
String msg = ""; public
void init()
{
os = new
Choice(); browser = new
Choice();
//add items to os list
[Link]("Windows 98/XP");
[Link]("Windows NT/2000");
[Link]("Solaris");
[Link]("MacOS");
\{ add items to browser list
[Link]("Netscape 3.x");
[Link]("Netscape 4.x");
[Link]("Netscape 5.x");
[Link]("Netscape 6.x");
[Link]("Internet Explorer4.0");
[Link]("InternetExplorer 5.0");
[Link]("Internet Explorer6.0");
[Link]("Lynx 2.4");

JAVA PROGRAMMING Page 70


MRCET JAVA NOTES [Link] -I SEM-2024-2025

[Link]("Netscape 4.x");

\{ add choice lists to


window add(os);
add(browser);
\{ register to receive item events
[Link](this);
[Link](this);
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
// Display current selections.
public void paint(Graphics g)
{ msg = "Current OS: ";
msg += [Link]();
[Link](msg, 6, 120);
msg = "Current Browser: ";
msg += [Link]();
[Link](msg, 6, 140);
}
}
Lists
The List class provides a compact, multiple-choice, scrolling selection list. Unlike the Choice object,
which shows only the single selected item in the menu, a List object can be constructed to show any
number of choices in the visible window. It can also be created to allow multiple selections. List
provides these constructors: List( )
List(int numRows )
List(int numRows , boolean multipleSelect )
A List box is similar to a choice box, it allows the user to select multiple items.
· To create a list box:
(or)
List lst = new List();
List lst = new List (3, true);
This list box initially displays 3 items. The next parameter true represents that the user can
select more than one item from the available items. If it is false, then the user can select only
one item.
= To add items to the list box: [Link]("text");
= To get the selected items: String x[] = [Link]();
= To get the selected indexes: int x[] = [Link] ();

JAVA PROGRAMMING Page 71


MRCET JAVA NOTES [Link] -I SEM-2024-2025

// Demonstrate Lists.
import [Link].*; import
[Link].*; import
[Link].*; /*
<applet code="ListDemo" width=300 height=180>
</applet>
*/
public class ListDemo extends Applet implements ActionListener
{
List os, browser;
String msg = "";
public void init()
{
os= new List(4, true);
browser = new List(4, false);
\} add items to os list
[Link]("Windows 98/XP");
[Link]("Windows NT/2000");
[Link]("Solaris");
[Link]("MacOS");
\} add items to browser list
[Link]("Netscape 3.x");
[Link]("Netscape 4.x");
[Link]("Netscape 5.x");
[Link]("Netscape 6.x");
[Link]("Internet Explorer 4.0");
[Link]("Internet Explorer 5.0");
[Link]("Internet Explorer6.0");
[Link]("Lynx 2.4");
[Link](1);
\} add lists to window
add(os);
add(browser);
// register to receive action events
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent ae)
{
repaint();
}
// Display current selections.
public void paint(Graphics g)
{
int idx[];

JAVA PROGRAMMING Page 72


MRCET JAVA NOTES [Link] -I SEM-2024-2025

msg = "Current OS: ";


idx = [Link]();
for(int i=0; i<[Link]; i++)
msg += [Link](idx[i]) + " ";
[Link](msg, 6, 120);
msg = "Current Browser: ";
msg += [Link]();
[Link](msg, 6, 140);
}
}
Scroll Bars
Scroll bars are used to select continuous values between a specified minimum and maximum.
Scroll bars may be oriented horizontally or vertically. Scrollbar class is useful to create
scrollbars that can be attached to a frame or text area. Scrollbars can be arranged vertically or
horizontally.
\{ To create a scrollbar : Scrollbar sb = new Scrollbar (alignment, start, step, min, max);
alignment: [Link], [Link]
start: starting value (e.g. 0)
step: step value (e.g. 30) // represents scrollbar length
min: minimum value (e.g. 0)
max: maximum value (e.g. 300)
· To know the location of a scrollbar: int n = [Link] ();
· To update scrollbar position to a new position: [Link] (int position);
· To get the maximum value of the scrollbar: int x = [Link] ();
· To get the minimum value of the scrollbar: int x = [Link] ();
· To get the alignment of the scrollbar: int x = getOrientation ();
This method return 0 if the scrollbar is aligned HORIZONTAL, 1 if aligned VERTICAL.

// Demonstrate scroll bars.

import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="SBDemo" width=300 height=200>
</applet>
*/
public class SBDemo extends Applet
implements AdjustmentListener, MouseMotionListener
{
String msg = "";
Scrollbar vertSB, horzSB;
public void init()
{
int width = [Link](getParameter("width")); int
height = [Link](getParameter("height"));

JAVA PROGRAMMING Page 73


MRCET JAVA NOTES [Link] -I SEM-2024-2025

vertSB = new Scrollbar([Link], 0, 1, 0, height);


horzSB = new Scrollbar([Link], 0, 1, 0, width);
add(vertSB);
add(horzSB);

// register to receive adjustment events


[Link](this);
[Link](this);
addMouseMotionListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent ae)
{
repaint();
}
// Update scroll bars to reflect mouse dragging.
public void mouseDragged(MouseEvent me)
{
int x = [Link]();
int y = [Link]();
[Link](y);
[Link](x);
repaint();
}
// Necessary for MouseMotionListener
public void mouseMoved(MouseEvent me) {
}
// Display current value of scroll bars.
public void paint(Graphics g) {
msg = "Vertical: " + [Link]();
msg += ", Horizontal: " + [Link]();
[Link](msg, 6, 160);
\} show current mouse drag position
[Link]("*", [Link](),
[Link]());
}
}
Graphics
The AWT supports a rich assortment of graphics methods. All graphics are drawn relative to
a window.
Graphics class and is obtained in two ways:
\} It is passed to an applet when one of its various methods, such as paint( ) or update( ),
is called.
\} It is returned by the getGraphics( ) method of Component.
Drawing Lines
Lines are drawn by means of the drawLine( ) method, shown here:
void drawLine(int startX, int startY, int endX, int endY)
drawLine( ) displays a line in the current drawing color that begins at startX,startY and ends
at endX,endY.
The following applet draws several lines:

JAVA PROGRAMMING Page 74


MRCET JAVA NOTES [Link] -I SEM-2024-2025

// Draw lines import


[Link].*; import
[Link].*; /*
<applet code="Lines" width=300
height=200> </applet>
*/

public class Lines extends Applet


{ public void paint(Graphics g)
{
[Link](0, 0, 100, 100);
[Link](0, 100, 100, 0);
[Link](40, 25, 250, 180);
[Link](75, 90, 400, 400);
[Link](20, 150, 400, 40);
[Link](5, 290, 80, 19);
}
}
Drawing Rectangles

The drawRect( ) and fillRect( ) methods display an outlined and filled rectangle, respectively.
They are shown here:
void drawRect(int top, int left, int width, int height)
void fillRect(int top, int left, int width, int height)
The upper-left corner of the rectangle is at top,left. The dimensions of the rectangle are specified by
width and height.
To draw a rounded rectangle, use drawRoundRect( ) or fillRoundRect( ), both shown here:
void drawRoundRect(int top, int left, int width, int height,int xDiam, int yDiam)
void fillRoundRect(int top, int left, int width, int height, int xDiam, int yDiam)
// Draw rectangles

import [Link].*;
import [Link].*;
/*
<applet code="Rectangles" width=300
height=200> </applet>
*/
public class Rectangles extends Applet
{
public void paint(Graphics g)
{
[Link](10, 10, 60, 50);
[Link](100,10, 60, 50);
JAVA PROGRAMMING Page 75
MRCET JAVA NOTES [Link] -I SEM-2024-2025

[Link](190, 10,60, 50, 15, 15);


[Link](70, 90,140, 100, 30, 40);
}
}

Drawing Ellipses and Circles


To draw an ellipse, use drawOval( ). To fill an ellipse, use fillOval( ). These methods are shown here:
void drawOval(int top, int left, int width, int height)
void fillOval(int top, int left, int width, int height)
// Draw Ellipses
import [Link].*;
import [Link].*; /*
<applet code="Ellipses" width=300
height=200> </applet>
*/
public class Ellipses extends Applet
{
public void paint(Graphics g)
{
[Link](10, 10, 50, 50);
[Link](100, 10, 75, 50);
[Link](190, 10, 90, 30);
[Link](70, 90, 140, 100);
}
}
Drawing Arcs
Arcs can be drawn with drawArc( ) and fillArc( ), shown here:
void drawArc(int top, int left, int width, int height, int startAngle,int sweepAngle)
void fillArc(int top, int left, int width, int height, int startAngle,int sweepAngle)
The arc is bounded by the rectangle whose upper-left corner is specified by top,left and whose width
and height are specified by width and height. The arc is drawn from startAngle through the angular
distance specified by sweepAngle. Angles are specified in degrees. Zero degrees is on the horizontal,
at the three o’clock position. The arc is drawn counterclockwise if sweepAngle is positive, and
clockwise if sweepAngle is negative. Therefore, to draw an arc from twelve o’clock to six o’clock,
the start angle would be 90 and the sweep angle 180.
Drawing Polygons
It is possible to draw arbitrarily shaped figures using drawPolygon( ) and fillPolygon(), shown here:
void drawPolygon(int x[ ], int y[ ], int numPoints)
void fillPolygon(int x[ ], int y[ ], int numPoints)

JAVA PROGRAMMING Page 76


MRCET JAVA NOTES [Link] -I SEM-2024-2025

The polygon’s endpoints are specified by the


The following applet draws an
coordinate pairs contained within the x and y hourglass shape:
arrays. The number of points defined by x // Draw Polygon
import
and y is specified by numPoints. There are [Link].*;
alternative forms of these methods in which import
[Link].*;
the polygon is specified by a Polygon object. /*
The following applet draws several arcs: <applet code="HourGlass"
width=230 height=210>
</applet>
*/
public class HourGlass extends Applet
{
//Draw Arcs import public void paint(Graphics g)
[Link].*; {
import [Link].*; int xpoints[] = {30, 200, 30, 200, 30};
/* int ypoints[] = {30, 30, 200, 200, 30};
<applet code="Arcs" int num = 5;
width=300 height=200> [Link](xpoints,ypoints, num);
</applet> }public void paint(Graphics g)
*/ {
public class Arcs extends Applet int xpoints[] = {30, 200, 30, 200, 30};
{ int ypoints[] = {30, 30, 200, 200, 30};
public void paint(Graphics g) int num = 5; [Link](xpoints,
{ ypoints, num);
[Link](10, 40, 70, 70, 0, 75);
}
[Link](100, 40, 70, 70, 0, 75);
[Link](10, 100, 70, 80, 0, 175);
[Link](100, 100, 70, 90, 0, 270);
[Link](200, 80, 80, 80, 0, 180);
}
}

SWINGS
Swing is a set of classes that provides more powerful and flexible components than are possible with
the AWT. Swing is a GUI widget toolkit for Java. It is part of Oracle's Java Foundation Classes
(JFC) that is used to create window-based applications. It is built on the top of AWT (Abstract
Windowing Toolkit) API and entirely written in java. In addition to the familiar components, such as
buttons, check boxes, and labels, Swing supplies several exciting additions, including tabbed panes,
scroll panes, trees, and tables. Even familiar components such as buttons have more capabilities in
Swing. For example, a button may have both an image and a text string associated with it. Also, the
image can be changed as the state of the button changes. Unlike AWT components, Swing

JAVA PROGRAMMING Page 77


MRCET JAVA NOTES [Link] -I SEM-2024-2025

components are not implemented by platform specific code. Instead, they are written entirely in Java
and, therefore, are platform-independent. The term lightweight is used to describe such elements.
The [Link] package provides classes for java swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Differences between AWT and Swing

AWT SWING
AWT components are called Heavyweight Swings are called light weight component because swing components
component. sits on the top of AWT components and do the work.
AWT components are platform dependent. Swing components are made in purely java and
they are platform independent.
AWT components require [Link] package. Swing [Link] require [Link]
AWT is a thin layer of code on top of the OS. Swing is much larger. Swing also has very much richer
functionality.
AWT stands for Abstract windows toolkit. Swing is also called as JFC’s (Java Foundation classes).
This feature is not supported in AWT. We can have different look and feel in Swing.
Using AWT, you have to implement a lot of Swing has them built in.
things yourself.
This feature is not available in AWT. Swing has many advanced features like JTabel, Jtabbed pane which is
not available in [Link] components are called“lightweight"
because they do not require a native OS object to implement their
functionality. JDialog and JFrame are heavyweight, because they do
have a peer. So components like JButton, JTextArea, etc., are
lightweight because they do not have an OS peer.

The Swing component classes are:


Class Description
AbstractButton Abstract superclass for Swing buttons.
ButtonGroup Encapsulates a mutually exclusive set of buttons.
ImageIcon Encapsulates an icon.
JApplet The Swing version of Applet.
JButton The Swing push button class.
JCheckBox The Swing check box class.
JComboBox Encapsulates a combo box (combination of a drop-down list & text field).
JLabel The Swing version of a label.

JAVA PROGRAMMING Page 78


MRCET JAVA NOTES [Link] -I SEM-2024-2025

JRadioButton The Swing version of a radio button.


JScrollPane Encapsulates a scrollable window.
JTabbedPane Encapsulates a tabbed window.
JTable Encapsulates a table-based control.
JTextField The Swing version of a text field.
JTree Encapsulates a tree-based control.

Hierarchy for Swing components:

JApplet

Fundamental to Swing is the JApplet class, which extends Applet. Applets that use Swing must
be subclasses of JApplet. JApplet is rich with functionality that is not foundin Applet.
The content pane can be obtained via the method shown here:
Container getContentPane( )
The add( ) method of Container can be used to add a component to a content pane. Its form is
shown here:
void add(comp)
Here, comp is the component to be added to the content pane.
JFrame
Create an object to JFrame: JFrame ob = new JFrame ("title"); (or)
Create a class as subclass to JFrame class: MyFrame extends JFrame

JAVA PROGRAMMING Page 79


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Create an object to that class : MyFrame ob = new MyFrame ();


Example: Write a program to create a frame by creating an object to JFrame
class. //A swing Frame
import [Link].*;
class MyFrame
{
public static void main (String agrs[])
{ JFrame jf = new JFrame ("My Swing Frame...");
[Link] (400,200);
[Link] (true);
[Link] (JFrame.EXIT_ON_CLOSE);
}
}

Note: To close the frame, we can take the help of getDefaultCloseOperation () method of
JFrame class, as shown here: getDefaultCloseOperation (constant);
where the constant can be any one of the following:
◼ JFrame.EXIT_ON_CLOSE: This closes the application upon clicking on close button.
◼ JFrame.DISPOSE_ON_CLOSE: This disposes the present frame which is visible on
the screen. The JVM may also terminate.
◼ JFrame.DO_NOTHING_ON_CLOSE: This will not perform any operation upon clicking
on close button.
◼ JFrame.HIDE_ON_CLOSE: This hides the frame upon clicking on close button.

Window Panes: In swings the components are attached to the window panes only. A window
pane represents a free area of a window where some text or components can be displayed. For
example, we can create a frame using JFrame class in [Link] which contains a free area inside
it, this free area is called 'window pane'. Four types of window panes are available in [Link]
package.
Glass Pane: This is the first pane and is very close to the monitors screen. Any components to
be displayed in the foreground are attached to this glass pane. To reach this glass pane, we use
getGlassPane () method of JFrame class.
Root Pane: This pane is below the glass pane. Any components to be displayed in the
background are displayed in this pane. Root pane and glass pane are used in animations also.
For example, suppose we want to display a flying aeroplane in the sky. The aeroplane can be
displayed as a .gif or .jpg file in the glass pane where as the blue sky can be displayed in the root

JAVA PROGRAMMING Page 80


MRCET JAVA NOTES [Link] -I SEM-2024-2025

pane in the background. To reach this root pane, we use getRootPane () method of JFrame class.
Layered Pane: This pane lies below the root pane. When we want to take several components
as a group, we attach them in the layered pane. We can reach this pane by calling getLayeredPane
() method of JFrame class.
Content Pane: This is the bottom most pane of all. Individual components are attached to this
pane. To reach this pane, we can call getContentPane () method of JFrame class.
Displaying Text in the Frame:
paintComponent (Graphics g) method of JPanel class is used to paint the portion of a component
in swing. We should override this method in our class. In the following example, we are writing
our class MyPanel as a subclass to JPanel and override the painComponent () method.

Write a program to display text in the frame


import [Link].*;
import [Link].*;
class MyPanel extends JPanel
{
public void paintComponent (Graphics g)
{
[Link] (g); //call JPanel’s method
setBackground ([Link]);
[Link] ([Link]);
[Link] (new Font("Courier New",[Link],30));
rawString ("Hello Readers!", 50, 100);
}
}
class FrameDemo extends JFrame
{ FrameDemo ()
{

JAVA PROGRAMMING Page 81


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Container c = getContentPane ();


MyPanel mp = new MyPanel ();
[Link] (mp);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{ FrameDemo ob = new FrameDemo ();
[Link] (600, 200);
[Link] (true);
}
}
TEXT FIELDS
The Swing text field is encapsulated by the JTextComponent class, which extends JComponent. It
provides functionality that is common to Swing text components. One of its subclasses is
JTextField, which allows you to edit one line of text.
Some of its constructors are shown here:
JTextField( )
JTextField(int cols)
JTextField(String s, int cols)
JTextField(String s)
import [Link].*;
import [Link].*;
/*
<applet code="JTextFieldDemo" width=300
height=50>
</applet>
*/
public class JTextFieldDemo extends JApplet
{
JTextField jtf;
public void init()
{
// Get content pane
Container contentPane = getContentPane();
[Link](new FlowLayout());
// Add text field to content
pane jtf = new
JTextField(15);
[Link](jtf);
}
}

JAVA PROGRAMMING Page 82


MRCET JAVA NOTES [Link] -I SEM-2024-2025

BUTTONS
Swing buttons provide features that are not found in the Button class defined by the AWT. For
example, you can associate an icon with a Swing button. Swing buttons are subclasses of the
AbstractButton class, which extends JComponent. AbstractButton contains many methods that
allow you to control the behavior of buttons, check boxes, and radio buttons.
The JButton Class
The JButton class provides the functionality of a push button. JButton allows an icon, a string, or
both to be associated with the push button. Some of its constructors are shown here:
· To create a JButton with text: JButton b = new JButton (“OK”);
· To create a JButton with image: JButton b = new JButton (ImageIcon ii);
· To create a JButton with text & image: JButton b = new JButton (“OK”, ImageIcon ii);
It is possible to create components in swing with images on it. The image is specified by

ImageIcon class object.


import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="JButtonDemo" width=250 height=300>
</applet>
*/
public class JButtonDemo extends JApplet implements ActionListener
{
JTextField jtf;
public void init()
{
// Get content pane
Container contentPane = getContentPane();
[Link](new FlowLayout());
// Add buttons to content pane
ImageIcon france = new ImageIcon("[Link]");
JButton jb = new JButton(france);
[Link]("France");
[Link](this); [Link](jb);
ImageIcon germany = new ImageIcon("[Link]");
jb = new JButton(germany);
[Link]("Germany");
[Link](this);
[Link](jb);
ImageIcon italy = new ImageIcon("[Link]");
jb = new JButton(italy);
[Link]("Italy");
[Link](this);
JAVA PROGRAMMING Page 83
MRCET JAVA NOTES [Link] -I SEM-2024-2025

[Link](jb);
ImageIcon japan = new ImageIcon("[Link]");
jb = new JButton(japan);
[Link]("Japan");
[Link](this);
[Link](jb);
// Add text field to
content pane jtf = new
JTextField(15);
[Link](jtf);
}
public void actionPerformed(ActionEvent ae)
{ [Link]([Link]());
}
}

CHECK BOXES
The JCheckBox class, which provides the functionality of a check box, is a concrete implementation
of AbstractButton. Its immediate superclass is JToggleButton, which provides support for two-state
buttons. Some of its constructors are shown here:
JCheckBox(Icon i)
JCheckBox(Icon i, boolean state)
JCheckBox(String s)
JCheckBox(String s, boolean state)
JCheckBox(String s, Icon i)
JCheckBox(String s, Icon i, boolean state)
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="JCheckBoxDemo" width=400 height=50>
</applet>
*/
public class JCheckBoxDemo extends JApplet implements ItemListener
{
JTextField jtf;
public void init()
{
// Get content pane
Container contentPane = getContentPane();
[Link](new FlowLayout());
// Create icons
ImageIcon normal = new ImageIcon("[Link]");
ImageIcon rollover = new ImageIcon("[Link]");
ImageIcon selected = new ImageIcon("[Link]");
// Add check boxes to the content pane
JCheckBox cb = new JCheckBox("C", normal);

JAVA PROGRAMMING Page 84


MRCET JAVA NOTES [Link] -I SEM-2024-2025

[Link](rollover);
[Link](selected);
[Link](this); [Link](cb);
cb = new JCheckBox("C++",
normal); [Link](rollover);
[Link](selected);
[Link](this);
[Link](cb);
cb = new JCheckBox("Java", normal);
[Link](rollover);
[Link](selected);
[Link](this);
[Link](cb);
cb = new JCheckBox("Perl", normal);
[Link](rollover);
[Link](selected);
[Link](this);
[Link](cb);

// Add text field to the content pane


jtf = new JTextField(15);
[Link](jtf);
}
public void itemStateChanged(ItemEvent ie)
{
JCheckBox cb = (JCheckBox)[Link]();
[Link]([Link]());
}
}
RADIO BUTTONS
Radio buttons are supported by the JRadioButton class, which is a concrete implementation of
AbstractButton. Its immediate superclass is
JToggleButton, which provides support for twostate
buttons. Some of its constructors are shown here:
JRadioButton(Icon i)
JRadioButton(Icon i, boolean state)
JRadioButton(String s)
JRadioButton(String s, boolean state)
JRadioButton(String s, Icon i)
JRadioButton(String s, Icon i, boolean state)
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="JRadioButtonDemo" width=300 height=50>
</applet>
*/
JAVA PROGRAMMING Page 85
MRCET JAVA NOTES [Link] -I SEM-2024-2025

public class JRadioButtonDemo extends JApplet implements ActionListener


{
JTextField tf;
public void init()
{
// Get content pane
Container contentPane = getContentPane();
[Link](new FlowLayout());
1. Add radio buttons to content pane
JRadioButton b1 = new JRadioButton("A");
[Link](this);
[Link](b1);
JRadioButton b2 = new JRadioButton("B");
[Link](this);
[Link](b2);
JRadioButton b3 = new JRadioButton("C");
[Link](this);
[Link](b3);
2. Define a button group
ButtonGroup bg = new ButtonGroup();
[Link](b1);
[Link](b2);
[Link](b3);
// Create a text field and add it
// to the content pane
tf = new JTextField(5);
[Link](tf);
}
public void actionPerformed(ActionEvent ae)
{
[Link]([Link]());
}
}
Limitations of AWT:
The AWT defines a basic set of controls, windows, and dialog boxes that support a usable, but limited
graphical interface. One reason for the limited nature of the AWT is that it translates its various visual
components into their corresponding, platform-specific equivalents or peers. This means that the look
and feel of a component is defined by the platform, not by java. Because the AWT components use
native code resources, they are referred to as heavy weight. The use of native peers led to several
problems.
First, because of variations between operating systems, a component might look, or even act,
differently on different platforms. This variability threatened java’s philosophy: write once, run
anywhere.

JAVA PROGRAMMING Page 86


MRCET JAVA NOTES [Link] -I SEM-2024-2025

Second, the look and feel of each component was fixed and could not be changed. Third, the use of
heavyweight components caused some frustrating restrictions. Due to these limitations Swing came
and was integrated to java.
Swing is built on the AWT. Two key Swing features are: Swing components are light weight, Swing
supports a pluggable look and feel.

JAVA PROGRAMMING Page 87

You might also like