Overview of JAVA
Overview of JAVA
Overview of JAVA
C C++ JAVA
Stages of development of Java
HISTORY OF JAVA:
In 1979 “Vinod Khosla” reached America & started a company named Sun Microsystem. JAVA
was developed by “JAMES GOSLING” in 1991, at Sun Microsystem to program electronic
devices later on it was modified as internet programming language. Its mother language was
OAK.
Features of JAVA:
Small
Secure
Robust (flexible)
Architecture Neutral
Multithreaded
Compiled + Interpreted
Platform Independent Language
Features of OOP’s:
1. Classes & objects
2. Reusability
3. Inheritance
4. Polymorphism
5. Encapsulation
6. Abstraction
First Program in java to print hello world:
Since java is pure object oriented programming language therefore a simple program will also
start with class.
class Program
{
public static void main(String args[])
{
System.out.println(“Hello World”);
}
}
class every program should have class to support Reusability (class is separate module with
respect to OOP). Every program is saved with the name of class. It is referred as beans on
internet
public is stand alone sharable program
static main program should be stable do not need objects.
void main it is declaration of main function, every compiler controlled language has main
function which guides compiler the starting of program. Void keyword ensures that main
function donot return any value.
String is default datatype in java. Each program in JAVA is a thread.
args[ ] or a[ ] array of output. For example: Hello World will be stored in array of args[] type.
Such that
args[0] = H, args[1] = e, args[2] = l, args[3] = l ……………………… args[10] = d.
Java converts all datatype in string for example:
class Program
{ In this case int a will be
public static void main(String args[]) converted to string and then
{ printed
int a=10
System.out.println(a);
}
}
System . out. println is a stream to print output. JAVA always transfers data from one file to
other or from one medium to another in form of streams (continous flow of data)
System it is class. In java name of all inbuild classes starts with capital letter.
out it is object os System class, used with dot operator.
println it is function of System class used to print output. It takes parameters in string. It prints
output in next line, to print output in same line we have function print.
Why prog is always saved with name of class (3 main reasons)
java file is converted into class file, compiler recognizes both file by their name.
as we use static in main its property is unchangeable , Name is also one of the property so it should also be
unchangeable.
A code is reusable so name should be stable, same for all users.
TROUBLE SHOOTING
to set environment
My computer
(Right click)
Properties
Tabbed window
Advanced
Environment variable
Path: C:\Jdk1.4\bin
class,<class name>
{
instances- variableset of variable defined inside class
methods/ functions.
}
obj are known as instance [changes value] with the user are instance variable]
class A Obj
class name A a = new A(); default Constructor
{
instance
} object new operator
1. Need of function
There are many reasons for using functions:
1. To cope with complex problems: with functions we can divide complex task into
smaller and easily understood task.
2. To hide low level details: once method is defined user need not know how ethod is
implementing its task. Thus low level details get hidden with methods.
3. To reuse portion of code: when one task is implemented using method then whenever
such task is neededthe same method is used without rewriting the code.
4. To create conceptual units: we can create methods/functions to do one action as single
conceptual unit, one function can use another function to accomplish the task.
// Method Call
int a=10,b=20;
int s = sum(a,b);
In this a, b are actual parameters
Benefit of this Method: In this method we cannot alter the variables that are used to call the
function because any change that occurs inside the function is on the function’s copy of
argument value. The original copy of argument value remains unchanged.
Benefit of this Method: This method is used when we want to change the original values using
function.
* In java all primitive types are passed by value and all reference types (objects, arrays) are
passed by reference.
Constructors:
Constructors are special type of function, which are used to initiallize the variables of class and
have same name as that of class.
Properties of constructors:
1. They have same name as that of class.
2. Are used to initiallize the variables of class.
3. Donot have any return type.
4. No need to call them expilicitly are automatically called when object is created
There are three types of constructors in java.
1. Default constructors
2. Parameterized constructors
3. Copy constructors
Default constructors:
It is basis of all constructors. It donot have any parameters. If constructor is not created in a
program then compiler automatically creates a default constructor and initializes all variables to
0.
Syntax: (Program.java)
class Box
{
double width,depth,height; // declaration of global variables
Box() // declaration of default constructor
{
width= 10; // initializing variables in default constructor
depth= 12;
height= 30;
}
}
class Program
{
public static void main(String args[ ])
{
Box b = new Box(); // calling default constructor, when object is created
double volume = b.width * b.height * b.depth;
System.out.println(“Volume of Box is ” + volume);
}
}
Parameterised constructors:
It is another type of constructor. It can take any number of parameters as arguments.
Syntax: (Program.java)
class Box
{
double width,depth,height; // declaration of global variables
Box(double w, double d, double h) // declaration of Parameterised constructor
{
width= w; // initializing variables in Parameterised constructor
depth= d;
height= h;
}
}
class Program
{
public static void main(String args[ ])
{
Box b = new Box(10,12,30); // passing parameters to Parameterised constructor,
double volume = b.width * b.height * b.depth; // when object is created
System.out.println(“Volume of Box is ” + volume);
}
}
Copy constructors:
This constructor passes object as an parameter.
Syntax: (Program.java)
class Box
{
double width,depth,height; // declaration of global variables
Box() // declaration of default constructor
{
width= 10; // initializing variables in default constructor
depth= 12;
height= 30;
}
Box( Box b) // declaration of Copy constructor
{
width= b.width; // initializing variables in Copy constructor
depth= b.depth;
height= b.height;
}
}
class Program
{
public static void main(String args[ ])
{
Box b = new Box(); // calling default constructor, when object is created
Box b1 = new Box(b); // passing object b of default constructor to Copy constructor
double volume = b1.width * b1.height * b1.depth;
System.out.println(“Volume of Box is ” + volume);
}
}
class Box
{
double width,depth,height; // declaration of global variables
Box() // declaration of default constructor
{
width= 10; // initializing variables in default constructor
depth= 12;
height= 30;
}
Box(double w, double d, double h) // declaration of Parameterised constructor
{
width= w; // initializing variables in Parameterised constructor
depth= d;
height= h;
}
Box( Box b) // declaration of Copy constructor
{
width= b.width; // initializing variables in Copy constructor
depth= b.depth;
height= b.height;
}
}
class Program
{
public static void main(String args[ ])
{
Box b = new Box(); // calling default constructor, when object is created
Box b1 = new Box(100,120,300); // passing parameters to Parameterised constructor
Box b2 = new Box(b); // passing object b of default constructor to Copy constructor
double volume;
volume = b.width * b.height * b.depth;
System.out.println("Volume of Box is (Default Constructor)" + volume);
volume = b1.width * b1.height * b1.depth;
System.out.println("Volume of Box is (Parameterised Constructor)" + volume);
volume = b2.width * b2.height * b2.depth;
System.out.println("Volume of Box is (Copy Constructor)" + volume);
}
}
Inheritance:
It is property of object oriented pogramming in which one class inherits the property of other
class so as to insure resuablty of that class. This class can modify the property of inherited class
and can reuse it as and when needed. It insures child parent relationship.
The class which inherits the property of other class is called “Sub class/ derived class /child
class”
The class whose properties are inherited is called “Super class/ base class/ parent class”
There are five type of inheritances:
Single level inheritance
Multi level inheritance
Multiple inheritance
Heirarical inheritance
Hybrid inheritance
Multiple inheritance
Heirarical inheritance
Hybrid inheritance
A
A (Super
class)
B
B(Sub
class) C
Abstract class:
It is a special type of class in which we have atleast one abstract function.
Abstract Function
Package
There are two types of packages
Inbuild Package
Userdefined Package
Inbuild Packages
There are 5 inbuild packages in java:
Java.lang
Java.io
Multithreading:
Process
Ready queue
Buffer1
Java multithreading support the concept of Preemptive scheduling algo after definite time job
stops and restart again when next job executes for sometime.
run
Wait start
new Ready queue exit
C.P.U
*to increase processing size increase processing speed of C.P.U and decrease waiting time of jo
new
exit wait
run start
Small Program are called treads one main prog. can have many treads
Multithreading Multiprogramming + time sharing
Java multithreading
Implemented in two different ways.
extends thread (class)
implement runnable (interface)
Thread class has many func. But runnable interface has only “run”() func
When we want to check property of thread then we use T.C and if we want to only run the
thread we will use Run interface.
Thread Class
Syntax of extending Thread class
class square extends Thread
{
public void run ()
{
}
}
class cube extends Thread
{
public void run ()
{
}
}
class Program
{
public static void main (String args[])
{
square S = new square(); // Thread S = new square();
cube C = new cube(); // Thread S = new cube();
S. start();
C. start();
}
}
In JAVA every prog. is a thread and have start () func.
Runnable Interface
Syntax of implementing Runnable
class square implements Runnable
{
public void run ()
{
}
}
class cube implements Runnable
{
public void run ()
{
}
}
class Program
{
public static void main (String args[])
{
square S = new square();
cube C = new cube();
Thread t1 = new thread(S);
Thread t2 = new thread(C);
t1. start();
t2. start();
}
}
Example of multithreading
using extends Thread
class square extends Thread
{
public void run ()
{
System.out. println ( "finding square of numbers:");
for (int i=1; i<=10 ; i++)
{
System.out. println ("square of " +i+ " = " + i*i);
}
}
}
class cube extends Thread
{
public void run ()
{
System.out. println ( "finding cube of numbers:");
for (int i=1; i<=10 ; i++)
{
System.out. println ("cube of " +i+ " = " + i*i);
}
}
}
class Program
{
public static void main (String args[])
{
square S= new square();
cube C= new cube();
S. start();
C. start();
}
}
using implements Runnable
Syncronization
Critical
mutex
semaphores
P1, P2, P3, ….., Pn have no relation with one another are Mutual exclusion
P1 threads or mutex.
Func() is shared between P1, P2, P3, ….,
P2
Func()
P3
Pn
Semaphoresis to avoid the condition of deadlock.
Wait & signal two variables are used in this.
If wait =0 the func. is free.
And signal=1
When wait=1, signal=0 wait is opposite to the signal.
S/w implementation of semaphores with the help of JAVA prog.
Semaphores: always only one process to be executed.
TRICK:
Class 1
Class 1 Execute
Func()
Class 2
Critical section
Class 3
To call critical section func.
class Callme
{
synchronized void call(String msg)
{
System.out.print("["+msg);
try
{
Thread. sleep (1000);
}
catch (InterruptedException e)
{
System.out.print("Exception");
}
System.out.print("]");
}
}
class Program
{
public static void main (String args[])
{
Callme target = new Callme();
Caller t1= new Caller("Hello",target);
Caller t2= new Caller("Java",target);
Caller t3= new Caller("World!",target);
try
{
t1.t.join();
t2.t.join();
t3.t.join();
}
catch (InterruptedException e2)
{
System.out.print("Exception");
}
}
}
for(i=0;i<l1;i++)
{
char ch1=str1.charAt(i);
if((ch1=='A')||(ch1=='E')||(ch1=='I')||(ch1=='O')||(ch1=='U')||(ch1=='a
')||(ch1=='e')||(ch1=='i')||(ch1=='o')||(ch1=='u'))
{
c++;
}
else if((ch1>='0') && (ch1<='9'))
{
j++;
}
}
System.out.println("Number of vowels is "+c);
System.out.println("Number of digits is "+j);
}
}
Array
Linear Search
import java.io.*;
class Arr
{
public static void main(String args[])throws IOException
{
int i,f=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a[]=new int[10];
for(i=0;i<10;i++)
{
System.out.println("Enter element of array");
String s1=br.readLine();
a[i] =Integer.parseInt(s1);
}
System.out.println("Enter element to be searched");
String s=br.readLine();
int n=Integer.parseInt(s);
for(i=0;i<10;i++)
{
if(a[i]==n)
{f=f+1;
}
}
if(f>0)
System.out.println("Element found "+ f +" time");
else
System.out.println("Element not found");
}
}
Binary Search
import java.io.*;
class Arr1
{
public static void main(String args[])throws IOException
{
int i,f=0,low,high,mid;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a[]=new int[10];
for(i=0;i<10;i++)
{
System.out.println("Enter element of array");
String s1=br.readLine();
a[i] =Integer.parseInt(s1);
}
low=0;
high=9;
System.out.println("Enter element to be searched");
String s=br.readLine();
int n=Integer.parseInt(s);
//first sort the array
while((low<=high)&&(f==0))
{
mid=(low+high)/2;
if(a[mid]==n)
f=mid;
else if(a[mid]>n)
high=mid-/7 1;
else
low=mid+1;
}
if(f>0)
System.out.println("Element found "+ (f+1) +" position");
else
System.out.println("Element not found");
}
}
Maximum and minium element in array
import java.io.*;
class Arr
{
public static void main(String args[])throws IOException
{
int i,f=0,min,max;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a[]=new int[10];
for(i=0;i<10;i++)
{
System.out.println("Enter element of array");
String s1=br.readLine();
a[i] =Integer.parseInt(s1);
}
min=a[0];
max=a[0];
for(i=1;i<10;i++)
{
if(min>a[i])
{min=a[i];
}
if(max<a[i])
{max=a[i];
}
}
System.out.println("Minimum element is "+min);
System.out.println("Maximum element is "+max);
}
}
O/P stream
Source Java Destination
I/P stream
stream
Byte Character
stream stream
Buffer
Byte Stream
9) Print stream
import Java.io.*;
class Program
{
public static void main (String args[]) throws IOException
{
InputStream f1= new fileInputStream (“file2.text”)
Byte Array Input stream bais = new Byte Array input stream(file)
String str = bais . read ();
System.out.println(“str”);
Byte Array Input stream bais1 = new Byte Array input stream(f1,0,3);
String str1 = bais1 . read ();
System.out.println(“str1”);
}
}
import java.io.*;
class pg
{
public static void main (String args[]) throws IOException
{
String str = "Abhilsaha";
byte b[]=new byte[20];
int l=str.length();
str.getBytes(0,l,b,0);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileOutputStream f1 = new FileOutputStream("file.text");
baos.write(b);
baos.writeTo(f1);
baos.close();
f1.close();
}
}
Buffered Input stream :
import Java.io.*;
class Program
{
public static void main (String args[]) throws IOException
{
file InputStream f1= new fileInputStream (“file2.text”)
Buffered Input stream bis = new Buffered input stream(f1);
Int ch;
While((ch=bis.read())!=-1)
{
String Buffer Sb1= new string buffer();
Sb1.append ((char)ch);
System.out.println(“str”);
}
f1.close();
bis.close();
}
}
import Java.io.*;
class Program
{
public static void main (String args[]) throws IOException
{
String str = “Abhilasha”
Byte b [] =new byte[64]
Str. Get Byte(0, str.length(), b, 0);
Buffered Output stream bos = new Buffered Output stream(System.out);
Bos.write(b,0,64);
[bos.flush()];
bos.close();
}
}
import Java.io.*;
class Program
{
public static void main (String args[]) throws IOException
{
file InputStream fis= new fileInputStream (“file2.text”)
Data Input stream dis = new Data input stream(fis);
System.out.println(dis.read Char());
System.out.println(dis.read .Int());
System.out.println(dis.read float());
fis.close();
dis.close();
}
}
import Java.io.*;
class Program
{
public static void main (String args[]) throws IOException
{
file OutputStream fos= new fileOutputStream (“file2.text”)
Data Output stream dos = new Data Output stream(fos);
dos.write Char(‘J’);
dos.write .Int(6);
dos.write float(33.67f);
fos.close();
dos.close();
}
}
Character Stream
In this content are transferred in form of characters. In Byte stream , these are following
classes:
1) BufferedReader
2) BufferedWriter
3) CharArrayReader
4) CharArrayWriter
5) FileReader
6) FileWriter
7) InputStreamReader
8) OutputStreamWriter
9) PushBackWriter
10) PrintWriter
11) Reader
BufferedReader
import java.io.*;
class Program
{
public static void main (String args[]) throws IOException
{
String str= "Welcome to Java";
FileWriter o1=new FileWriter("file1.txt");
BufferedWriter b1 = new BufferedWriter(o1);
b1.write(str);
b1.flush();
b1.close();
o1.close();
}
}
import java.io.*;
class Program
{
public static void main (String args[]) throws IOException
{
String str;
InputStreamReader o1=new InputStreamReader(System.in);
BufferedReader b1 = new BufferedReader(o1);
System.out.println("Enter String");
str=b1.readLine();
System.out.println("You Typed :----> "+str);
b1.close();
o1.close();
}
}
BufferedWriter
CharArrayReader
import java.io.*;
class Program
{
public static void main (String args[]) throws IOException
{
int l,k;
char x[]=new char[64];
char ch;
String str="This is the test string";
l=str.length();
str.getChars(0,l,x,0);
CharArrayReader car= new CharArrayReader(x);
for(int i=0;i<l;i++)
{
k=car.read();
ch=(char)k;
System.out.println("You Typed :----> "+ch);
}
car.close();
}
}
CharArrayWriter
import java.io.*;
class Program
{
public static void main (String args[]) throws IOException
{
int l,k;
char x[]=new char[64];
char ch;
String str="This is the test string";
l=str.length();
str.getChars(0,l,x,0);
CharArrayWriter car= new CharArrayWriter();
for(int i=0;i<l;i++)
{
ch=(char)x[i];
System.out.println(ch);
}
car.close();
}
}
FileReader
FileWriter
InputStreamReader
OutputStreamWriter
PushBackWriter
PrintWriter
Reader
File Class
Applets:
It is used for GUI programming in java.
1. Java Appplet Coordinates
Increasing x
Increasing y
initialize start
stop
destroy
java.applet.*;
java.awt.*;
public class program extends Applet
{
public void init()
{
}
public void start()
{
}
public void stop()
{
}
public void destroy()
{
}
public void paint(Graphics g)
{
}
}
Component Programming
AWT (Abstract Window Toolkit): atleast one function need to be used add()
Container (Applet)
Windows
All component should be initialized using function: public void init()
Two method
→ using Panel
→ using LayoutManager
1) Panel → is object which hold other object. It also starts from center to right. To see panel we
need to change its background color , because by default its color is same as color of container.
import java.awt.*;
import java.applet.*;
public class program extends Applet
{
public void init()
{
Panel p = new Panel();
Button b1= new Button("SAVE");
Button b2= new Button("CANCEL");
p.setBackground(Color.blue);
p.add(b1);
p.add(b2);
add(p);
}
}
Layout Manger
Flow Layout Grid Layout Border Layout Card Layout Grid Bag Layout
Functions in Applet
Donot functions in
Applet
a) Flow Layout :→
import java.awt.*;
import java.applet.*;
public class program extends Applet
{
public void init()
{
FlowLayout flow = new FlowLayout(FlowLayout.RIGHT);
setLayout(flow);
Button b1= new Button("SAVE");
Button b2= new Button("CANCEL");
Button b3= new Button("EXIT");
setBackground(Color.blue);
add(b1);
add(b2);
add(b3);
}
}
b) Grid Layout :→
import java.awt.*;
import java.applet.*;
public class program extends Applet
{
public void init()
{
GridLayout grid = new GridLayout (3,3,10,10);
setLayout(grid);
Button b1= new Button("1");
Button b2= new Button("2");
Button b3= new Button("3");
Button b4= new Button("4");
Button b5= new Button("5");
Button b6= new Button("6");
Button b7= new Button("7");
Button b8= new Button("8");
Button b9= new Button("9");
setBackground(Color.pink);
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
add(b6);
add(b7);
add(b8);
add(b9);
}
}
Also try:
GridLayout grid = new GridLayout (2,3,10,10);
GridLayout grid = new GridLayout (1,3,10,10);
GridLayout grid = new GridLayout (3,3);
West
East
Center
South
import java.awt.*;
import java.applet.*;
public class program extends Applet
{
public void init()
{
BorderLayout border = new BorderLayout (10,10);
setLayout(border);
Button b1= new Button("1");
Button b2= new Button("2");
Button b3= new Button("3");
Button b4= new Button("4");
Button b5= new Button("5");
setBackground(Color.magenta);
add(b1,"North");
add(b2,"South");
add(b3,"East");
add(b4,"West");
add(b5,"Center");
}
}
import java.awt.*;
import java.applet.*;
public class program extends Applet
{
public void init()
{
CardLayout card = new CardLayout (10,10);
setLayout(card);
Label lbl[] = new Label[2];
lbl[0]= new Label("A is label");
lbl[1]= new Label("B is label");
setBackground(Color.green);
for (int i=0;i<=1;i++)
{
add("Card" + i,lbl[i]);
card.show(this,"Card"+i);
}
}
}
Also try : for (int i=0;i<1;i++)
Frames
Frame is a child window. Minimum, maximum works but exit does not.
Functions:
S. No Function Name Description
1 setResizable(True/False) If it is true then we can change the size of the
By default: True frame, if not then we cannot.
2 setTitle(String) For giving title to frame
3 reshape(x,y,width,height) For changing size of frame
4 show() Used for displaying frame
import java.awt.*;
import java.applet.*;
public class program extends Applet
{
public void init()
{
Frame f = new Frame();
f.setResizable(true);
f.setTitle("Frame Test");
f.reshape(10,10,250,250);
f.show();
}
}
Also try: f.setResizable(False);
Menus
There is only one menu bar inside a container or frame. It contains three things:
a) MenuBar
b) Menu
c) MenuItem
import java.awt.*;
import java.applet.*;
public class program extends Applet
{
Frame f;
MenuBar mbar;
Menu m;
MenuItem mitem;
public void init()
{
f = new Frame();
mbar = new MenuBar();
m= new Menu("File",true);
mbar.add(m);
mitem= new MenuItem("Exit");
m.add(mitem);
f.setMenuBar(mbar);
f.reshape(10,10,250,250);
f.setBackground(Color.pink);
f.show();
}
}
Scroll Bar
Java File:
import java.awt.*;
import java.applet.*;
public class program extends Applet
{
String str;
public void init()
{
str=getParameter("message");
}
public void paint(Graphics g)
{
g.drawString(str,25,25);
}
}
HTML File:
<HTML>
<HEAD><TITLE>Applet Test</TITLE></HEAD>
<BODY>
<APPLET CODE="program.class" WIDTH="400" HEIGHT="400">
<PARAM NAME=message VALUE="Welcome to world of JAVA">
</APPLET>
</BODY>
</HTML>
click Button
Predefined
Function
Event Handling
When we click Button, it calls its Listener (Interface) which calls its predefined function that handles its even
Types of Listeners
Java.awt.event
Action Event Adjustment Event Component Event Item Event Text Event
(Action Listener) (Adjustment Listener) (Component Listener) (Item Listener) (Text Listener)
Sample Programs
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class program extends Applet implements ActionListener
{
Button b1,b2,b3;
String str;
public void init()
{
b1= new Button("RED");
b2= new Button("GREEN");
b3= new Button("BLUE");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
add(b1);
add(b2);
add(b3);
}
public void actionPerformed(ActionEvent e)
{
str = e.getActionCommand();
if(str.equals("RED"))
{
setBackground(Color.red);
}
if(str.equals("GREEN"))
{
setBackground(Color.green);
}
if(str.equals("BLUE"))
{
setBackground(Color.blue);
}
repaint(); // it changes with reference to white
}
}
repaint (x,y,width,height) :→ for specific part of Applet.
Also try:
public void actionPerformed(ActionEvent e)
{
if(e.getSource() = = b1)
{
setBackground(Color.red);
}
if(e.getSource() = = b2)
{
setBackground(Color.green);
}
if(e.getSource() = = b3)
{
setBackground(Color.blue);
}
repaint();
}
}
this:→ is used when the function called is inside the class itself
2) Program to input data in one Text Field and send it to another Text Field
(Action Listener).
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class program extends Applet implements ActionListener
{
TextField t1,t2;
Button b1,b2;
String str;
public void init()
{
t1 = new TextField(20);
t2 = new TextField(20);
b1= new Button("Press Me");
b2= new Button("Clear");
t2.setEnabled(false);
t1.requestFocus();
b1.addActionListener(this);
b2.addActionListener(this);
add(t1);
add(t2);
add(b1);
add(b2);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
str= t1.getText();
t2.setText(str);
}
if(e.getSource()==b2)
{
t1.setText(" ");
t2.setText(" ");
}
}
}
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class program extends Applet implements AdjustmentListener
{
Scrollbar sb;
int val1; // Scrollbar returns int value
public void init()
{
setLayout (new BorderLayout());
sb = new Scrollbar();
//sb.addListener(this);
add(sb,"west");
}
public void adjustmentValueChanged(AdjustmentEvent e)
{
val1 = e.getValue();
System.out.println(val1);
}
}
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class program extends Applet implements ItemListener
{
TextField t1;
Choice ch;
String str;
public void init()
{
ch = new Choice();
ch.add("Apple");
ch.add("Mango");
ch.add("Banana");
ch.add("Papaya");
ch.addItemListener(this);
t1 = new TextField(20);
add(ch);
add(t1);
}
public void itemStateChanged(ItemEvent e)
{
str= ch.getSelectedItem();
t1.setText(str + " is my favorite Fruite");
if(str.equals("Apple"))
{
t1.setBackground(Color.pink);
}
if(str.equals("Mango"))
{
t1.setBackground(Color.yellow);
}
if(str.equals("Banana"))
{
t1.setBackground(Color.red);
}
if(str.equals("Papaya"))
{
t1.setBackground(Color.green);
}
}
}