Advanced Java Notes

122
POTHURAI To store 100 objects of employee class: - A group of objects can be stored in any array but there are two limitations. 1) It is not possible to store different class objects in to the same array. 2) Methods are not available to process the elements of the array. java.util Objects Collection class Collection object Container A collection object or container object is an object that stores a group of other objects. A collection class or container class is a class whose class object can store a group of other class. What is collection frame work ? It represents group of classes. It is a class library to handle groups of objects. Collection frame work implemented java.util package Note : - Collection objects stores only references. (Collection object does not store other object. It requires group of objects) Objects Object reference SUDHEER REDDY 1

Transcript of Advanced Java Notes

Page 1: Advanced Java Notes

POTHURAI

To store 100 objects of employee class: - A group of objects can be stored in any array but there are two limitations.1) It is not possible to store different class objects in to the same array.2) Methods are not available to process the elements of the array.

java.util Objects

Collection class

Collection object Container A collection object or container object is an object that stores a group of other objects. A collection class or container class is a class whose class object can store a group of other class.

What is collection frame work? It represents group of classes. It is a class library to handle groups of objects. Collection frame work implemented java.util packageNote: - Collection objects stores only references. (Collection object does not store other object. It requires group of objects)

Objects

Object reference

Collection object can not handle (does not store) primitive data type.

All the classes in collection frame work have been defined in 3 types. They are 1) Sets 2) Lists 3) Maps.

1) Sets : - A set represents a group of elements. Ex: - Hash set, linked hash set, Tree set.2) Lists: - A list also similar to sets, a list is like an array which stores a group of events (events means elements). Sets will not allow duplicate values, where as list will allows duplicates values also. Ex: - linked list, Array list, and vector. 3) Maps: - A map stores the elements in the form of key valve pairs. Ex: - Hash table, Hash map.

Array List: - It is dynamically glowing array that stores objects. It is not synchronized.

SUDHEER REDDY

1

Page 2: Advanced Java Notes

POTHURAI

Processing Processing simultaneously

Only one thread allows the object, it is called synchronized. Or more than 1 object can not take object is called as synchronized.

Several threads take at a time is called unsynchronized.

1) To create an array list. ArrayList arl = new ArrayList( ); ArrayList arl = new ArrayLlist (20);

2) To add objects; use add ( ) method.arl.add(“sudheer”);arl.add(2,“sudheer”);

3) To remove objects use remove ( )arl.remove(“sudheer”);arl.remove(2);

4) To know no. of objects use size ( )int n=arl.size( );

5) To convert ArrayList in to an arry use .toArray( )object x[ ]=arl.toArray( ); Object is super class for all class.

// creating an array list import java.util.*;class ArrayaListDemo{

public static void main(String[] args) {

// creating an array listArrayList arl=new ArrayList( );// store elements in to arlarl.add("apple");arl.add("banana");arl.add("pine apple");arl.add("grapes");arl.add("mango");//display the contents of arlSystem.out.println("ArrayList = "+arl);// remove some elements from arlarl.remove("apple");arl.remove(1);// display the contents of arlSystem.out.println("ArrayList = "+arl);// find no of elements in url

SUDHEER REDDY

2

Page 3: Advanced Java Notes

POTHURAI

System.out.println("size of lists = "+arl.size( ));// retrieve the elements using iteratorIterator it=arl.iterator( );while(it.hasNext( ))System.out.println(it.next( ));

}}

D:\psr\Adv java>javac ArrayaListDemo.javaD:\psr\Adv java>java ArrayaListDemoArrayaList = [apple, banana, pine apple, grapes, mango]ArrayaList = [banana, grapes, mango]size of lists = 3bananagrapesmango

Note: - to extract the events one by one from collection objects we can use only one of the following

1) Iterator2) ListIterator3) Enumeration

Vectors: - It is a dynamically growing array that stores objects, but it synchronized.

1) To crate a vectorVector v=new Vector( );Vector v=new Vecteor(100);

2) To know the size of a vector use size( )int n=v.size( );

3) To add elementsv.add(obj);v.add(2,obj);

4) to retrieve elements v.get(2);

5) To remove elementsv.remove( );To remove all elementsv.clear( );

6) To know the current capacityint n=v.capacity( );

7) To search for first occurrence of an element in the vectorint n=v.indexOf(obj)

8) To search for last occurrence of an elementint n=v.lastIndexOf(obj);

SUDHEER REDDY

3

Page 4: Advanced Java Notes

POTHURAI

// a vector with int values import java.util.*;class VectorDemo{

public static void main(String[] args) {

// creating an vector vVector v=new Vector( );// take an int type of array x[]int x[]={10,33,45,67,89};// read from x[] & store into vfor(int i=0;i<x.length;i++){

v.add(new Integer(x[i]));}// retrieve objects using get( )for(int i=0;i<v.size( );i++){System.out.println(v.get(i));}// retrieve elements from v using IteratorListIterator lit=v.listIterator( );System.out.println("\n in forward Direction :");while(lit.hasNext( ))System.out.println(lit.next ( )+"");System.out.println("\n reverse Direction :");while(lit.hasPrevious( ))System.out.println(lit.previous( )+"");

}}

D:\psr\Adv java>javac VectorDemo.javaD:\psr\Adv java>java VectorDemo10 33 45 67 89 in forward Direction :10 33 45 67 89 reverse Direction :89 67 45 33 10

Hashtable: - Hashtable Stores objects in the form of keys & values pairs. It is synchronized. It will not allow more threads at a time.1) To create a hash table.

HashTable ht=new HashTable( );// initial capacity=11, load factor=0.75HashTable ht=new HashTable(100);

2) To store key value pairht.put(“Sunil”, cricket player);

SUDHEER REDDY

4

Page 5: Advanced Java Notes

POTHURAI

3) To get the value when key is givenht.get(“Sunil”);

4) To remove the key (and its corresponding value)ht.remove(“Sunil”);

5) To know the no. of keys int n=ht.size( );

6) To clear all the keysht.clear( );

What is load factor?A) Load factor determines at what point the initial capacity of a hash table or a hash map will be double. Load factor is 0.75 of hash table.

For a hash table initial capacity x load factor = 11x0.75=8 approximately. It means after storing 8th key value pair will be doubled=22.

// Hashtable with cricket scores import java.io.*;import java.util.*;class HashtableDemo{

public static void main(String[] args) throws IOException{

// create hash tableHashtable ht=new Hashtable( );// store player name & scoreht.put("Sachin",new Integer(320));ht.put("Ganguli",new Integer(300));ht.put("Dravid",new Integer(150));ht.put("Dhoni",new Integer(100));ht.put("Yuvaraj",new Integer(56));ht.put("Sehwag",new Integer(000));// retrieve keys & displayEnumeration e=ht.keys( );while(e.hasMoreElements( ))System.out.println(e.nextElement( ));// to accept the data BufferedReader br=new BufferedReader(new

InputStreamReader(System.in));System.out.println("Enter player name:");String name=br.readLine( );// pass name & storeInteger score=(Integer)ht.get(name);if(score!=null){

int runs=score.intValue( );System.out.println(name+" has scored runs "+runs);

}

SUDHEER REDDY

5

Page 6: Advanced Java Notes

POTHURAI

else{

System.out.println("player not found");}

}}

D:\psr\Adv java>javac HashtableDemo.javaD:\psr\Adv java>java HashtableDemoYuvarajGanguliDhoniSehwagDravidSachinEnter player name: Ganguli has scored runs 300

Hash map: - Stores objects in the form of keys & value pairs. It is synchronized.1) To create a hash table

HashMap hm=new HashMap( )// initial capacity=11, load factor=0.75HashMap hm=new HashMap(100);

2) To store key value pairhm.put(“Sunil”, cricket player);

3) To get the value when key is givenhm.get(“Sunil”);

4) To remove the key (and its corresponding value)hm.remove(“Sunil”);

5) To know the no. of key value pairs.int n=hm.size( );

6) To clear all the key value pairshm.clear( );

// Hash map with telephone entries import java.io.*;import java.util.*;class HashMapDemo{

public static void main(String[] args) throws IOException{

// varsHashMap hm=new HashMap( );BufferedReader br=new BufferedReader(new

InputStreamReader(System.in));String name,str;long phno;

SUDHEER REDDY

6

Page 7: Advanced Java Notes

POTHURAI

// menuwhile(true){

System.out.println("1.Enter entries into phone book");System.out.println("2. Look up in phone book");int n=Integer.parseInt(br.readLine( ));switch(n){

case 1:System.out.println("Enter name : ");name=br.readLine( );System.out.println("Enter phone number : "); str=br.readLine( );phno=new Long(str);hm.put(name,phno);break;

case 2:System.out.println("Enter name : ");name=br.readLine( );phno=(Long)hm.get(name);System.out.println("Phone number : "+phno);break;

default :return;

}}

}}

D:\psr\Adv java>javac HashMapDemo.javaD:\psr\Adv java>java HashMapDemo1. Enter entries into phone book2. Look up in phone book1Enter name:SunilEnter phone number:2472831. Enter entries into phone book2. Look up in phone book2Enter name:SunilPhone number: 2472831. Enter entries into phone book2. Look up in phone book3

SUDHEER REDDY

7

Page 8: Advanced Java Notes

POTHURAI

What is the difference between Vector & array list ? A) 1) From the API perspective, the two classes are same. 2) Vector is synchronized & array list is not synchronized. Note: - We can make array list also synchronized by using:

Collections. synchronizedList(new ArrayList( ));3) Internally both are hold onto their contents using an array. A vector by default increments its size by doubling it, & on array list increases its size by 50%.4) Both are good for retrieving elements from a specific position in the container or for adding & removing elements from the end of the container. All of these operations can be performed in constant time---0(1), but adding & removing elements in the middle takes more time. So in this case a linked list is better.

What is the difference between hash table & hash map?A) 1) Hash table is a synchronized, where as hash map is not. Note: - We can make hash map also synchronized by using:

Collections. synchronizedList(new HashMap( ));2) Hash map allows null values as keys & values, where as hash table does not.3) That iterator in the hash map is fail-safe, while enumerator for the hash table isn’t.

What is the difference between a set & list?A) 1) Sets represent collection of elements. Lists represent ordered Collection of elements (also called sequence). 2) Sets will not allow duplicates values. Lists will allow. 3) Accessing elements by their index is possible in lists. 4) Sets will not allow null elements, lists allow null elements.

StringTokenizer: - The StringTokenizer class is useful to break a string into small piece called tokens.1) To crate an object to StringTokenizer

StringTokenizer st=new StringTokenizer(str,”delimeter”);Delimerer means character

2) To find the next piece in the stringString piece=st.nextToken( );

3) To know if more pieces are remaining boolean x=st.hasMoreTokens( );

4) To know how many no. of piece are thereint no=st.countTokens( );

The purpose of StringTokenizer is to cut the tokens into piece.

// to cut the string into piece import java.util.*;class STDemo{

public static void main(String[ ] args) {

SUDHEER REDDY

8

Page 9: Advanced Java Notes

POTHURAI

// take a stringString str="Sunil Kumar Reddy\ is a nice gentle men\ and genious";// cut str into pieces where space is poundStringTokenizer st=new StringTokenizer(str,"\");// retrieve tokens & displaySystem.out.println("the Tokens are ::");while(st.hasMoreTokens( )){

String s=st.nextToken( );System.out.println(s);

} }}

D:\psr\Adv java>javac STDemo.javaD:\psr\Adv java>java STDemoSunil Kumar Reddyis a nice gentle menand genious

Calendar: - This class is useful to handle date & time.1) To create an object to Calendar class

Calendar cl=Calendar.getInstance( );2) Use gets to retrieve date or time from Calendar object. This method returns an integer.

cl.get(Constant);Note: - Constants

Calendar.DATECalendar.MONTHCalendar.YEARCalendar.HOURCalendar.MINUTECalendar.SECOND

3) Use set ( ) to the set the date or time cl.set(Calendar.MONTH,10); // jan0

4) To convert a date in to string, use toStirng( ), this returns a String.String s=cl.toString( );

// System date & time import java.util.*;class Cal{

public static void main(String[] args) {

// create calendarCalendar cl=Calendar.getInstance( );// retrieve data

SUDHEER REDDY

9

Page 10: Advanced Java Notes

POTHURAI

int dd=cl.get(Calendar.DATE);int mm=cl.get(Calendar.MONTH);++mm;int yy=cl.get(Calendar.YEAR);System.out.print("Current date : ");System.out.println(dd+"/"+mm+"/"+yy);//retrieve timeint h=cl.get(Calendar.HOUR);int m=cl.get(Calendar.MINUTE);int s=cl.get(Calendar.SECOND);System.out.print("Current time : ");System.out.println(h+":"+m+":"+s);

}}

D:\psr\Adv java>javac Cal.javaD:\psr\Adv java>java CalCurrent date : 28/8/2007Current time : 11:48:34

Date: - Date class is an also useful to handle Date & time.

1) To create an object to Date classDate d=new Date( );

2) Format the Date & time, using getDateInstance( ) or getTimeInstance( ) or getDateTimeInstance( ) methods of Date format class (this is in java.text)

Syntax: -DateFormat fmt.getDateInstance(formatConst, region);EX: -DateFormat fmt.getDateInstance(DateFormat.MEDIUM,Locale UK);Syntax: - DateFormat fmt=DateFormat.getDateTimeInstance(formatConst,

formatConst,region);Ex: -DateFormat fmt=DateFormat.getDateTimeInstance

(DateFormat.MEDIUM,DateFormat.SHORT,Locale.US);Note: - formatConst example (region=Locale.UK)DateFormat.LONG 03 September 2004 19:43:14 GMT+0.5:30DateFormat.FULL 03 September 2004 19:43:14 o’ clock GMT+05:30DateFormat.MEDIUM 03-Sep-04 19:43:14DateFormat.SHORT 03/09/04 19:43

3) Applying format to date object is done by format( ) method.String str=fmt.format(d);

SUDHEER REDDY

10

Page 11: Advanced Java Notes

POTHURAI

// System date & time import java.util.*;import java.text.*;class MyDate{

public static void main(String[] args) {

// create date class objDate d=new Date( );// format date & timeDateFormat fmt=DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.SHORT,Locale.US);// apply format to dString s=fmt.format(d);// display formated time & dateSystem.out.println(s);

}}

D:\psr\Adv java>javac MyDate.javaD:\psr\Adv java>java MyDateAug 28, 2007 11:52 PM

Streams: - A stream represents flow of data from one place to another place. There are 2 types.

1) Input streams : - It read or receives data.2) Output streams : - It sends or writes data.

Other type of classifications.1) Byte streams: - These streams handle data in the form of bits & bytes2) Text streams: - These streams handle data in the form of individual character.All the streams are represented by classes in java.io package.

1) To handle data in the form of ‘bytes’: - (The abstract classes: input stream & output stream): -

InputStream

FileInputStream FilterInputStream ObjectInputStream

BufferedInputStream DataInputStream

SUDHEER REDDY

11

Page 12: Advanced Java Notes

POTHURAI

OutputStream

FileOutputStream FilterOutputStream ObjectOutputStream

BufferedOutputStream DataOutputStream

a) FileInputStream / FileoutputStream: - They handle data to be read or written to disk files.b) FilterInputStream / FilterOutputStream: - They read from one stream and write into another stream.c) ObjectInputStream / ObjectOutputStream:- They handle storage of objects and primitive data.

2) To handle date in the form of ‘text’: - (The abstract classes: Reader and writer)

Reader

BufferedReader CharArrayReader InputStramReader PrintReader

FileReader

Writer

BufferedWriter CharArrayWriter InputStramWriter PrintWriter

FileWriter

a) BufferedReader /BufferedWriter: - Handles characters (text) by buffering them. They provide efficiency.b) CharArrayReader/CharArrayWriter: - Handle array of character.c) InputStreamReader/OutputStreamWriter: - They are bridge between bytes streams & character streams. Readers read bytes and then decode them into 16-bit Unicode characters. Writers decode characters into bytes then write.d) PrintReader/PrintWriter: - Handle printing of characters, on the screen.

SUDHEER REDDY

12

Page 13: Advanced Java Notes

POTHURAI

DataInputStream FileOutputStream

System.in

// creating a file import java.io.*;class Create1{

public static void main(String[] args) throws IOException{

// attach keyboard to dataInputStreamDataInputStream dis=new DataInputStream(System.in);// attach my file to FileOutputStreamFileOutputStream fout=new

FileOutputStream("myfile",true);BufferedOutputStream bout=new

BufferedOutputStream(fout,1024);// read data from dis & write into foutchar ch;System.out.println("Enter data(@ at end):");while((ch=(char)dis.read( ))!='@')bout.write(ch);// close the filebout.close( );

}} fout

10 sec 10 sec total1 1 24 sec1 1

bout 1 total1 1 13 sec10 sec

So, we used the bout in the above program.

D:\psr\Adv java>javac Create1.javaD:\psr\Adv java>java Create1Enter data (@ at end):Hai I am Sunil Kumar Reddy. My hobbies are playing Cricket, playing Chess & reading Books. My favorite actor is Junior N.T.R. My favorite actress is Maanya

SUDHEER REDDY

13

Keyboard MyFile

Page 14: Advanced Java Notes

POTHURAI

My dream girl name is Latha. She is one of the beautiful girls in the world. She always laughs. That laughs attract me. I am also best friend of her. @

D:\psr\Adv java>type myfileHai I am Sunil Kumar Reddy. My hobbies are playing Cricket, playing Chess & reading Books. My favorite actor is Junior N.T.R. My favorite actress is Maanya

My dream girl name is Latha. She is one of the beautiful girls in the world. She always laughs. That laughs attract me. I am also best friend of her.

FileInputStream

// to read data from a text file import java.io.*; System.outclass Read1{

public static void main(String[] args) throws IOException{

try{ // accept file name from kayboardBufferedReader br=new BufferedReader(new

InputStreamReader(System.in));System.out.print("enter a file name :");String fname=br.readLine( );//attach my file to FileInputStreamFileInputStream fin=new FileInputStream(fname);BufferedInputStream bin=new BufferedInputStream(fin);// read data from fin & displayint ch;while((ch=bin.read( ))!=-1)System.out.print((char)ch);// close the filebin.close( );}catch(FileNotFoundException fe){

System.out.println("Sorry,file not found");}

}}

SUDHEER REDDY

14

MyFile Monitor

Page 15: Advanced Java Notes

POTHURAI

D:\psr\Adv java>javac Read1.javaD:\psr\Adv java>java Read1enter a file name :myfileHai I am Sunil Kumar Reddy. My hobbies are playing Cricket, playing Chess & reading Books. My favorite actor is Junior N.T.R. My favorite actress is Maanya

My dream girl name is Latha. She is one of the beautiful girls in the world. She always laughs. That laughs attract me. I am also best friend of her.

// creating a file import java.io.*;class Create2{

public static void main(String[] args) throws IOException{

// take a stringString str="This is an institute "+"\n I am a student here";// take a file & attah in to FileWriterFileWriter fw=new FileWriter("textfile");BufferedWriter bw=new BufferedWriter(fw,1024);// read data from str & write in to fwfor(int i=0;i<str.length( );i++)

bw.write(str.charAt(i));// close the filebw.close( );

}}

D:\psr\Adv java>javac Create2.javaD:\psr\Adv java>java Create2D:\psr\Adv java>type textfileThis is an institute I am a student here

// read data from textfile import java.io.*;class Read2{

public static void main(String[] args) throws IOException{

// attach textfile to FileReaderFileReader fr=new FileReader("textfile");BufferedReader br=new BufferedReader(fr);// read data from fr & displayint ch;while((ch=br.read( ))!=-1)System.out.print((char)ch);// close the file

SUDHEER REDDY

15

Page 16: Advanced Java Notes

POTHURAI

br.close( );}

}

D:\psr\Adv java>javac Read2.javaD:\psr\Adv java>java Read2This is an institute I am a student here

To zip the contents: -DeflaterOutputStream.

To unzip the file: -InflaterInputStream.

These classes are include in java.util.zip package

File1 File2

//to zip the file contents import java.io.*;import java.util.zip.*; class Compress { public static void main(String[] args) throws Exception

{ // attach file1 to FileInputStream FileInputStream fis=new FileInputStream("file1"); // attach file2 to FileOutputStream FileOutputStream fos=new FileOutputStream("file2"); // attach fos to DeflaterOutputStream DeflaterOutputStream dos=new DeflaterOutputStream(fos); // read data from fis & write in to dos int data; while((data=fis.read( ))!=-1)

dos.write(data); // close the files fis.close( ); dos.close( );}

}

D:\psr\Adv java>javac Compress.javaD:\psr\Adv java>edit file1D:\psr\ Adv java>type file1

SUDHEER REDDY

16

fis dos

fos

Page 17: Advanced Java Notes

POTHURAI

Hai i am Sunil Kumar ReddyMy pet name is Sudheer Reddy……

D:\psr\Adv java>java CompressD:\psr\Adv java>dir file*.* Volume in drive D is DISK Volume Serial Number is 280A-AE9B Directory of D:\psr\Adv java08/29/2007 04:48 PM 353 file108/29/2007 04:48 PM 71 file2 2 File(s) 424 bytes 0 Dir(s) 9,683,542,016 bytes free

D:\psr\Adv java>type file2x£≤H╠T╚TH╠.═╦╠Q≡.═M,JMI⌐Σσ≥¡T(H-Q╚K╠MU╚,♠¬H╔HMà╩*((≡ryÉ⌐yΣΦΣσ☻ æ☼r╠

//to unzip the file contents import java.io.*;import java.util.zip.*; class UnCompress{ public static void main(String[] args) throws Exception

{ // attach file2 to FileInputStream FileInputStream fis=new FileInputStream("file2"); // attach file3 to FileOutputStream FileOutputStream fos=new FileOutputStream("file3");

// attach fis to InflaterInputStream InflaterInputStream iis=new InflaterInputStream(fis); // read data from iis & write in to fos int data; while((data=iis.read( ))!=-1)

fos.write(data); // close the files iis.close( ); fos.close( );}

}

D:\psr\Adv java>javac UnCompress.javaD:\psr\Adv java>java UnCompressD:\psr\Adv java>dir file*.* Volume in drive D is DISK

SUDHEER REDDY

17

Page 18: Advanced Java Notes

POTHURAI

Volume Serial Number is 280A-AE9B Directory of D:\psr\Adv java08/29/2007 04:48 PM 353 file108/29/2007 04:48 PM 71 file208/29/2007 04:54 PM 353 file3 3 File(s) 777 bytes 0 Dir(s) 9,683,546,112 bytes free

D:\psr\Adv java>type file3Hai i am Sunil Kumar ReddyMy pet name is Sudheer Reddy…… Net working:-

Inter connection of a computer as called network. Resource sharing is the main advantage of network. Internet is a global network of several computers existing on the earth.

Web browser

Web Server

Web browser: - The software that initial on in internet client machine is called Web browser.Web Server: - The software that should be installed on in a internet server machine is called Web Server.

A client is a machine that sends request for some service. A server is a machine that provides services to the clients. A network is also called client server model. There are 3 requirements of network.

1) Hard ware : - you need cables, satellite etc.2) Soft ware : - web logic, web spear, iis, Apache, jobs.3) Protocol : - A protocol is specification of rules to be followed by every

computer on the network.

A protocol represents a set of rules to be followed by every computer on the internet or any network.TCP / IP: - (transmission control protocol / international protocol) is used to send or receive the text. A packet contain group of bytes.UDP: - (user datagram protocol) is used to transmit videos, audios & images.

SUDHEER REDDY

18

ClientServer

Page 19: Advanced Java Notes

POTHURAI

HTTP: - (hyper text transfer protocol) it is most widely used protocol on internet. It is used to receiving the web pages.FTP: - (file transfer protocol) is used to down load the files.POP: - (post office protocol) is used to receive mails from mail box.

Different protocols are used on internet.

IP address: - IP address is a unique id number allotted to every computer on the network. The computers on a network are identified because of IP address uniquely.DNS: - Domain naming service or system. It is a service that maps the website names corresponding IP address.

.comcommercial website

.edueducational website

.milmilitary people commercial website www.yahoo.com

192.100.56.01

Code (root directory) It is code for starting html file

There are 5 types of IP address: -

class A

16,777,216 hostsclass B

65,536 hostsclass C

256 hostsclass D

Research class E

Socket: - A socket is a point of connection between the server & client. Data flow is move one place to another place.

Socket

Port number is an identification number given to the socket. Every new socket should have a new port number.

SUDHEER REDDY

19

0 Network 7 Local Address 24

Local Address 16

Local Address 8

Network14

Network 21

10

110

S C

Page 20: Advanced Java Notes

POTHURAI

Establishing communication between server & client: - Using a socket is called socket programming.Server socket class: - It is useful to create server side socketSocket class: - It is useful to create client side socket.

// a server that sends message to clients import java.io.*;import java.net.*;class Server1{

public static void main(String args[]) throws Exception{

// create server side socket default port noServerSocket ss=new ServerSocket(777);// server waits till a connection is accepted by the clientSystem.out.println("Server is waiting......");Socket s=ss.accept( );System.out.println("connected to client");// attach output stream to socketOutputStream obj=s.getOutputStream( );// to send data till the socketPrintStream ps=new PrintStream(obj);// send data from serverString str="Hello Client ";ps.println(str);ps.println("How are you ?");ps.println("Bye");// disconnect serverps.close( );ss.close( );s.close( );

}}

D:\psr\adv java>javac Server1.java

SUDHEER REDDY

20

S

C

S

C

Page 21: Advanced Java Notes

POTHURAI

// a server that sends message to clients import java.io.*;import java.net.*;class Client1{

public static void main(String args[] ) throws Exception{

// create client side socketSocket s=new Socket("localhost",777);// add inputstream to the socketInputStream obj=s.getInputStream( );// to recieve data from socketBufferedReader br=new BufferedReader(new

InputStreamReader(obj));// now receive dataString str;while((str=br.readLine( ))!=null)

System.out.println(str);// disconnect servers.close( );br.close( );

}}

Compile: - compile & run the above 2 programs in 2 dos prompts on same time.D:\psr\adv java>javac Client1.java

D:\psr\adv java>java Server1 D:\psr\adv java>java Client1Server is waiting...... Hello Clientconnected to client How are you ?

Bye

It is possible to run several JVM’S simultaneously in same computer system.

Communicating from server: - 1) Create a server socket

ServerSocket ss=new ServerSocket(port no);2) Accept any client connection

Socket s=ss.accept( );3) To send data, connect the output stream to the socket

OutputStream obj=s.getOutputStream( );4) To receive data from the client, connect input stream

InputStream obj=s.getInputStream( );5) Send data to the client using print stream

PrintStream ps=new PrintStream(obj);ps.print(str);ps.println(str);

SUDHEER REDDY

21

Page 22: Advanced Java Notes

POTHURAI

6) Read data coming from the client using buffered readerBufferedReader br=new BufferedReader(new

InputStreamReader(System.in(obj));ch=br.read( );str=br.readLine( );

Communicating from client: - 1) Create a client socket

Socket s=new Socket (“IP address”, port no );2) To send data, connect the OutputStream to the socket

OutputStream obj=s.getOutputStream( );3) To receive data from the server, connect Input stream to the socket

InputStream obj=s.getInputStream( );4) Send data to the server using data output stream.

DataOutputStream dos=new DataOutputStream(obj);dos.writeBytes(str);

5) Read data coming from the server using BRBufferedReader br=new BufferedReader(new

InputStreamReader(System.in(obj));ch=br.read( ); str=br.readLine( );

Closing communication: - close all streams & socketsps.close( );br.close( );dos.close( );ss.close( );s.close( );

// chat server import java.io.*;import java.net.*;class Server2{

public static void main(String[] args) throws Exception{

// create ServerSocketServerSocket ss=new ServerSocket(999);// wait till a client connection acceptedSocket s=ss.accept( );System.out.println("Connection established.....");// send data to clientPrintStream ps=new PrintStream(s.getOutputStream( ));// to recive data from clientBufferedReader br=new BufferedReader(new

InputStreamReader(s.getInputStream( )));// to read from keyboardBufferedReader kb=new BufferedReader(new

SUDHEER REDDY

22

1) local object 2) remote object : - it is an object that is created another JVM, which is existing on the network. it can be accessed through references.

Page 23: Advanced Java Notes

POTHURAI

InputStreamReader(System.in));// communication with clientwhile(true){

String str,str1;while((str=br.readLine( ))!=null){

System.out.println(str);str1=kb.readLine( );ps.println(str1);

}//disconnect the Serverps.close( );br.close( );kb.close( );ss.close( );s.close( );System.exit(0);

}}

}

D:\psr\adv java>javac Server2.java

// chat Client import java.io.*;import java.net.*;class Client2{

public static void main(String[] args) throws Exception{

// create ClientSocketSocket s=new Socket("localhost",999);// send data to ServerDataOutputStream dos=new

DataOutputStream(s.getOutputStream( ));// to receive data from ServerBufferedReader br=new BufferedReader(new

InputStreamReader(s.getInputStream( )));// to read data from keyboardBufferedReader kb=new BufferedReader(new

InputStreamReader(System.in));// communication with clientString str,str1;while(!(str=kb.readLine( )).equals("exit")){

dos.writeBytes(str+"\n");

SUDHEER REDDY

23

Page 24: Advanced Java Notes

POTHURAI

str1=br.readLine( );System.out.println(str1);

}//disconnect the Servers.close( );dos.close( );br.close( );kb.close( );

}}

D:\psr\adv java>javac Client2.java

D:\psr\adv java>java Server2 D:\psr\adv java>java Client2Connection established..... Hellow! How r u?Hellow! How r u? I am fine. Who r u?I am fine. Who r u? I am Usha Rani. What's ur name?I am Usha Rani. What's ur name? My name is Harinath Reddy. Any My name is Sudheer Reddy. Any way I will chat later with u. Bye ra. way I will chat later with u. Bye ra. Smile pleaseSmile please OK tomorrow I will meat u. Bye.OK tomorrow I will meat u. Bye. exit

Threads: - A thread represents a process or execution of statements.

// finding the presenting running thread class MyClass{

public static void main(String[] args) {

System.out.println("This is Thread Program !");Thread t=Thread.currentThread( );System.out.println("Currently running thread ="+t);System.out.println("Its name ="+t.getName( ));

}}

D:\psr\Adv java>javac MyClass.javaD:\psr\Adv java>java MyClassThis is Thread Program !Currently running thread =Thread[main,5,main]Its name =main

Which is the thread internally running in every java program?A) Main thread.

SUDHEER REDDY

24

Page 25: Advanced Java Notes

POTHURAI

What is the difference between thread & process?A) Process is a heavy weight, means it takes more memory & more processor time. A thread is a light weight process, means it takes less memory & less processor time.

1 min priority, 5 normal priority, 10 max priority.5 is the default priority. Every thread group can have name. in every java program main thread which executes first. Executing the statements is of two ways: -

1) Single tasking : - Executing only one task at a time is called single tasking.Micro Processor

Programs

--Time

The micro processor’s time is vested in between the tasks. Param is first super computer in India.2) Multi tasking: -

Part of the micro processor time allotted to each task.

Micro Processor

Memory

0.25 ms 0.25 ms 0.25 ms 0.25 ms

Round robin: - Executing all the tasks in cyclic manner is called round robin method. Time slice is the part of time allotted from each task.

Executing several tasks simultaneously by the micro possessor is called multi tasking. There are 2 types.

SUDHEER REDDY

25

Tasks

Page 26: Advanced Java Notes

POTHURAI

a) Process based multi tasking : - Executing several programs at a time is called process based multi tasking.

b) Thread based multi tasking : - Using multiple threads to execute different blocks of code is called thread based multi tasking.

Processor time is utilize in optimum way is the main advantage of multi tasking.

Uses of threads: - 1) Threads are used in creation of server software to handle multiple clients.2) Threads are used in animation & games development.

Crating a thread: -1) Write a class as a sub class to thread class.

class MyClass extends Thread (or)Write a class as an implementation class for runnable interface.class MyClass implements Runnable

2) Write run method with body in the classpublic void run( ){statements;}

Note: - Any thread can recognize only run method. A thread executes only the run method.

3) Create an object to classMyClass mc=new MyClass( );

4) Create a thread & attach to the objectThread t=new Thread(obj);

5) Run the threadt.start( );

// creating a thread import java.io.*;class Myclass extends Thread{

public void run( ){

boolean x=false;for(int i=1;i<100000;i++){

System.out.println(i);if(x) return;

}}

}class TDemo

SUDHEER REDDY

26

Page 27: Advanced Java Notes

POTHURAI

{public static void main(String[] args) throws IOException{

Myclass obj=new Myclass( );Thread t=new Thread(obj);t.start( );System.in.read( ); //wait till enter pressedobj.x=true;

}}

D:\psr\Adv java>javac TDemo.javaD:\psr\Adv java>java TDemo1234

How can you stop in the thread in the middle?A) 1) Declare the boolean type of variable & initialize at false

boolean x=flase; 2) If the variable value is true , “x” return from the method.

If(x) return; 3) To stoop the thread store true in to the variable

System.in.read( );obj.x=true;

Multi threading: - Using more than one thread is called multi threading. It is used in multi tasking.

What the difference is between extends Thread & implements runnable?A) Functionally both are same. If we use extends Thread then there is no scope to extend another class. Multiple inheritances are not supported in java.

class MyClass extends Thread,Frame // invalidBut if we write implements Runnable then there is still scope to extends some other class.

class MyClass implements Thread,Frame // validSo implements Runnable is more advantage of than extends.

// 2 threads act on 2 obj class Theatre implements Runnable{

String str;Theatre(String str){

this.str=str;}

SUDHEER REDDY

27

Page 28: Advanced Java Notes

POTHURAI

public void run( ){

for(int i=1;i<=10;i++){

System.out.println(str+":"+i);try{

Thread.sleep(2000);}catch (InterruptedException ie){

ie.printStackTrace( );}

}}

}class TDemo1{

public static void main(String[] args) {

Theatre obj1=new Theatre("cut Ticket ");Theatre obj2=new Theatre("Show Chairs");Thread t1=new Thread(obj1);Thread t2=new Thread(obj2);t1.start( );t2.start( );

}}

D:\psr\Adv java>javac TDemo1.javaD:\psr\Adv java>java TDemo1cut Ticket :1Show Chairs:1cut Ticket :2Show Chairs:2…… cut Ticket :10Show Chairs:10

// 2 threads acting on same thread class Reserve implements Runnable{

int wanted;int available=1;Reserve(int i){

SUDHEER REDDY

28

Page 29: Advanced Java Notes

POTHURAI

wanted=i;}public void run( ) {

synchronized(this) {

System.out.println("Available no. of berths = "+available);

if(available>=wanted) {

String name=Thread.currentThread( ).getName( ); System.out.println(wanted+"Berths allotted for "+name);

try {

Thread.sleep(2000); available-=wanted;

}catch(InterruptedException ie)

{ } }else{

System.out.println("Sorry, Berths not available "); }

}}

}class Safe{

public static void main(String[] args) {

// create an obj to reserve classReserve obj=new Reserve(1);// create 2 Threads & attach them tp objThread t1=new Thread(obj);Thread t2=new Thread(obj);// set names to Threadst1.setName("1st person");t2.setName("2nd Person");// run the Threadst1.start( );t2.start( );

}}

D:\psr\Adv java>javac Safe.java

SUDHEER REDDY

29

Page 30: Advanced Java Notes

POTHURAI

D:\psr\Adv java>java SafeAvailable no. of berths = 11Berths allotted for 1st personAvailable no. of berths = 0Sorry, Berths not available

Thread synchronization: - When a thread is acting on an object, preventing any other threads from acting on the same object is called synchronization of threads. This is also called thread safe. The synchronized object is called locked object or mutex (mutually exclusive lock). When ever multi threading is used we must synchronized the threads. There are 2 ways.

1) We can synchronize a block of statements using synchronized block.Ex: - synchronized(obj)

{ Statements;}

2) We can synchronize an entire method by writing synchronized keyword before a methodEx: - synchronized void MyMethod( )

{Method statements;

}

Deadlock: - When a thread wants to act on an object which has been already locked by another thread & the second thread wants to act on the first object. Which is locked by the first thread, both the threads would be in waiting state forever. This is called deadlock of threads.

In thread deadlock the program halts & any further processing is supported.

Cancel ticket

Comp

Train

Book ticket

// Cancel the ticket class CancleTicket extends Thread{

Object train,comp;

SUDHEER REDDY

30

100

200

Page 31: Advanced Java Notes

POTHURAI

CancleTicket(Object train,Object comp){

this.train=train;this.comp=comp;

}public void run( ){

synchronized(comp){

System.out.println("Cancel ticket has locked compartment");try{

sleep(100);}catch (InterruptedException ie){}

System.out.println("Cancel ticket has to lock train....");synchronized(train){

System.out.println("Cancel ticket has locked train");}

}}

}

D:\psr\Adv java>javac CancleTicket.java

// Booking a ticket class BookTicket extends Thread{

Object train,comp;BookTicket(Object train,Object comp){

this.train=train;this.comp=comp;

}public void run( ){

synchronized(train){

System.out.println("Cancel ticket has locked train");try{

sleep(200);}catch (InterruptedException ie)

SUDHEER REDDY

31

Page 32: Advanced Java Notes

POTHURAI

{}

System.out.println("Cancel ticket has to lock compartment....");synchronized(comp){

System.out.println("Cancel ticket has locked compartment");}

}}

}

D:\psr\Adv java>javac BookTicket.java

// Cancel & Book tickets simultaneously class DeadLock{

public static void main(String[] args) {

// take train , compartment as objects of objectObject train=new Object( );Object comp=new Object( );// create object to Cancle ticket, book ticketCancleTicket obj1=new CancleTicket(train,comp);BookTicket obj2=new BookTicket(train,comp);// create 2 threads & attach to obj'sThread t1=new Thread(obj1);Thread t2=new Thread(obj2);// run the threadst1.start( );t2.start( );

}}

D:\psr\Adv java>javac DeadLock.javaD:\psr\Adv java>java DeadLockCancel ticket has locked compartmentCancel ticket has locked trainCancel ticket has to lock train....Cancel ticket has to lock compartment....

There is no solution for thread deadlock. The programmer should take care not to form deadlock while designing the program.

Thread class methods: -1) To know the currently running thread: Thread t= Thread.currentThread ( );

SUDHEER REDDY

32

Page 33: Advanced Java Notes

POTHURAI

2) To start a thread: t. start ( );3) To stop execution or a thread for a specified time: Thread.Sleep(mille seconds); 4) To get the name of a thread. String name = t.getName ( );

5) To set a new name to a thread: t.setName( “name”);6) To get the priority of a thread: int priority_no = t.getPriority ( );7) To set the priority of a thread: t.setPriority( int priority_no);

Note: - The priority no. Constances are as given below. Thread.MAX_PRIORITY value is 10 Thread.MIN_PRIORITY value is 1. Thread.NORM_PRIORITY value is 5. 8) To test is a thread is still alive: t.isAlive( ) returns true/false. 9) To wait till a thread dies: t.join( ); 10) To send a notification to a waiting thread: obj.notify ( );11) To send notification of all waiting thread: obj.notifyAll ( );12) To wait till the obj is released (till notification is sent): obj.wait ( );Note: - The above 3 methods belong to object class.

String Buffer

Consumer Producer

// Thread communication: -class Communicate {

public static void main(String[] args) throws Exception{

// create producer & consumer obj's

SUDHEER REDDY

33

sbdata prod over

ProdFalse

Page 34: Advanced Java Notes

POTHURAI

Producer obj1=new Producer( );Consumer obj2=new Consumer(obj1);// creates threads & attach from obj'sThread t1=new Thread(obj1);Thread t2=new Thread(obj2);// start the Threadst1.start( );t2.start( );

}}class Producer extends Thread{

// to store dataStringBuffer sb;// to represent data production over or not// boolean dataprodover=false;Producer( ){

// allot memory to sbsb=new StringBuffer( );

}public void run ( )

{synchronized(sb)

{// create 10 itemsfor(int i=1;i<=10;i++)

{try{

sb.append(i+":");sleep(100);System.out.println("Appending..........");

}catch (Exception e){}

}// inform the consumer that the production over//dataprodover=true;sb.notify( );}

}}class Consumer extends Thread{

// to access producer members

SUDHEER REDDY

34

Page 35: Advanced Java Notes

POTHURAI

Producer prod;Consumer(Producer prod){

this.prod=prod;}public void run( ){

synchronized(prod.sb){try{

/*while(!prod.dataprodover){

sleep(10); // check every 10 ms} */prod.wait( );

}catch (Exception e){}}// now use data of sbSystem.out.println(prod.sb);

}}

D:\psr\Adv java>javac Communicate.javaD:\psr\Adv java>java CommunicateAppending..........Appending..........Appending..........Appending..........Appending..........Appending..........Appending..........Appending..........Appending..........Appending..........1:2:3:4:5:6:7:8:9:10:

In thread communications notify, notifyAll, wait are used for efficient communication.

Thread group: - A thread group represents a group of threads.1) Creating a thread group

ThreadGroup tg=new ThreadGroup(“group name”);

SUDHEER REDDY

35

Page 36: Advanced Java Notes

POTHURAI

2) To add a thread to this group tgThread t1=new Thread(tg, target obj, “thread name”);

3) To add another thread group to this group.ThreadGroup tg1=new ThreadGroup(tg, “group name”);

Daemon thread: - Daemon threads are service provides for other threads or objects. A daemon

thread execute continuously. It is generally provides a background processing.1) To make a thread as a daemon thread

t.setDaemon(true);2) To know if a thread is a daemon or not

boolean x=t.isDaemon( ); tg

// using thread group class WhyTGroup{

public static void main(String[] args) throws Exception{

Reservation res=new Reservation( );Cancellation can=new Cancellation( );// create a thread group with name

ThreadGroup tg=new ThreadGroup("Reservation Group");// create 2 threads & add them to thread groupThread t1=new Thread(tg,res,"firstThread");Thread t2=new Thread(tg,res,"secondThread");

// create another thread group as a child to tg ThreadGroup tg1=new ThreadGroup(tg,"Cancellation group");

// create 2 threads & add them to 2 thread groupThread t3=new Thread(tg,can,"thridThread");Thread t4=new Thread(tg,can,"fourthThread");

System.out.println("no.of threads in this group ="+tg.activeCount( ));// find parent group of tg1System.out.println("Parent of tg1 = "+tg1.getParent( ));// set mam priority to tg1 as 7tg1.setMaxPriority(7);// know the thread group of t1 & t3

SUDHEER REDDY

36

t1t2

tg1

res

cant3t4

Page 37: Advanced Java Notes

POTHURAI

System.out.println("ThreadGroup of t1 ="+t1.getThreadGroup( )); System.out.println("ThreadGroup of t3 ="+t3.getThreadGroup( ));

// start the threadst1.start( );t2.start( );t3.start( );t4.start( );

System.out.println("no.of threads in this group ="+tg.activeCount( ));}

}class Reservation extends Thread{

public void run( ){

System.out.println("I am a reservation Thread");}

}class Cancellation extends Thread{

public void run( ){

System.out.println("I am a Cancellation Thread");}

}

D:\psr\Adv java>javac WhyTGroup.javaD:\psr\Adv java>java WhyTGroupno.of threads in this group = 0Parent of tg1 = java.lang.ThreadGroup[name=Reservation Group ,maxpri=10]ThreadGroup of t1 = java.lang.ThreadGroup[name=Reservation Group

,maxpri=10]ThreadGroup of t3 = java.lang.ThreadGroup[name=Reservation Group

,maxpri=10]I am a reservation Threadno. of threads in this group = 3I am a reservation ThreadI am a Cancellation ThreadI am a Cancellation Thread

What is Thread life cycle: - A thread is crated by creating on object to thread class. The thread is executed by using start method. When the thread is started it goes into runnable state. Yield method passes the thread but still the thread will be in runnable state.

The thread wills coming to not runnable state, when sleep or wait methods are used or if it is blocked on I/O the thread is not runnable state. From this state, it comes into runnable state after some time. A thread will die when it comes out of run method.

SUDHEER REDDY

37

Page 38: Advanced Java Notes

POTHURAI

runnable

start

sleep( ) wait( ) if run( ) blocked on I / O

terminates

The above states from the birth of a thread till its death are called life cycle of a thread.

User interaction with an application is 2 types.1) CUI: - Character user interface.

In CUI the user will type commands or characters. It is not user friendly because the user should remember the commands.2) GUI: - graphical user interface.

User interaction with the application through graphics or pictures is called GUI. Advantages of GUI are given below.

1) GUI is user friendly.2) Using GUI we can design the application in an attractive manner.3) Using GUI we can simulate (create a model of real) object.4) We can create components like push button, Radio button, check boxes, menus, frames,…. etc

Component means graphical representation of an object. Component means push button.Ex: - Button b=new Button (“ok”)

TO develop GUI programs we can use java,awt& javax.swing packages we used in java.

Frame is a basic component. Layout manager is an interface that arranges the components on the screen; layout manager is implemented in the following classes

|-FlowLayout|-BorderLayout

Object------------------|-GridLayout|-CardLayout|-GridBagLayout

A box shaped area on the screen is called a window. A frame is a window that contains a title bar, borders, minimize & maximize buttons etc.

SUDHEER REDDY

38

yield

runnable

new thread

dead

not runnable

Page 39: Advanced Java Notes

POTHURAI

java.awt package: - awt means abstract window tool kit. That provides a set of classes & interfaces to create GUI programs.

|-Label|-Button|-Checkbox

Object---------Component------------------|-Choice |-List |-CanvasCheckbox Group |-Scroll bar |Text

| | field|-Text component---|| |Text| Area|-Container

-------------------------------------

Panel Window

Applet Frame

Crating a frame: - 1) Create on object

Frame f=new Frame ( );2) Crate a class as a sub class to frame class & then create to object on that class.

MyClass obj=new MyClass; (or)MyFrame obj=new MyFrame( );

(0,0) W (0.800)

H

(600,800) (800,600)

// creating a frame import java.awt.*;class MyFrame1{

public static void main(String[] args)

SUDHEER REDDY

39

800

600

Page 40: Advanced Java Notes

POTHURAI

{// create on obj to frameFrame f=new Frame( );// increase the w&hf.setSize(500,450);// display the framef.setVisible(true);

}}

D:\psr\Adv java>javac MyFrame1.javaD:\psr\Adv java>java MyFrame1

Pixel: - Pixel is short form picture element.

// creating a frame - v 2.0 import java.awt.*;class MyFrame2 extends Frame{

public static void main(String[] args) {

// create on obj to frameFrame f=new Frame( );// increase the w&hf.setSize(500,450);// give a title for framef.setTitle("P.SUDHEER REDDY");// display the framef.setVisible(true);

}}

D:\psr\Adv java>javac MyFrame2.javaD:\psr\Adv java>java MyFrame2

SUDHEER REDDY

40

Page 41: Advanced Java Notes

POTHURAI

Event: - User interaction with a component is called an event.Ex: - Clocking as an event, onmouseover, key pressed in keyboard, right clicking on event, text field, etc.

push button interfece call

call

call

The method is handling the event.

awt components obey event delegation model. In this model user interact with the component generating events. This event is delegated to listener by the component.

Delegation: - Hand over event to listenerListener is an interface that contains some abstract methods. Listener will

delegate the event to one of its methods. Finally the methods are executed & the event is handled. This is called event delegation model. In event delegation model the following steps are used

1) Add a listener to the component.2) Implements the methods of listener interface.

It is this model is useful to provide actions for awt components.3) When the event is generated listener will execute one or more

methods.

// creating a frame import java.awt.*;import java.awt.event.*;class MyFrame3 extends Frame{

public static void main(String[] args) {

// create on obj to frameFrame f=new Frame( );// increase the w&hf.setSize(500,450);// give a title for framef.setTitle("P.SUDHEER REDDY");// display the framef.setVisible(true);// add window listener to framef.addWindowListener(new Myclass( ));

}}class Myclass implements WindowListener{

SUDHEER REDDY

41

m1

m2

m3

ListenerOK

Page 42: Advanced Java Notes

POTHURAI

public void windowActivated(WindowEvent e){ }public void windowClosed(WindowEvent e){ }public void windowClosing(WindowEvent e)

{System.exit(0);}

public void windowDeactivated(WindowEvent e){ }public void windowDeiconified(WindowEvent e){ }public void windowIconified(WindowEvent e){ }public void windowOpened(WindowEvent e){ }

}(or)

// creating a frame import java.awt.*;import java.awt.event.*;class MyFrame4 extends Frame{

public static void main(String[] args) {

// create on obj to frameFrame f=new Frame( );// increase the w&hf.setSize(500,450);// give a title for framef.setTitle("P.SUDHEER REDDY");// display the framef.setVisible(true);// add window listener to framef.addWindowListener(new Myclass( ));

}}class Myclass extends WindowAdapter{

public void windowClosing(WindowEvent e){

System.exit(0);}

}

What is an adapter class?A) An adapter class is an implementation class of a listener interface where all the methods will have empty body. For example window adapter is an adapter class window listener class.class Myclass extends WindowAdapter{

public void windowClosing(WindowEvent e)

SUDHEER REDDY

42

Page 43: Advanced Java Notes

POTHURAI

{System.exit(0);

}} What is anonymous (means 1) inner class?A) It is an inner class whose name is not maintained & for which only one object is created to MyClass

f.addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent e){

System.exit(0);}

});(or)

// creating a frame import java.awt.*;import java.awt.event.*;class MyFrame5 extends Frame{

public static void main(String[] args) {

// create on obj to frameFrame f=new Frame( );// increse the w&hf.setSize(500,450);// give a title for framef.setTitle("P.SUDHEER REDDY");// display the framef.setVisible(true);// add window listener to framef.addWindowListener(new WindowAdapter( ){

public void windowClosing(WindowEvent e){

System.exit(0);}

});}

}

The frame is useful to do the following: -1) To display messages or Strings2) To display images & photos 3) To display components like push buttons, radio buttons, menu’s etc…

SUDHEER REDDY

43

Page 44: Advanced Java Notes

POTHURAI

1) Displaying a message in the frame: - To display strings or message in the frame we should use drawString ( ) method of Graphics class.Ex: - g.drawString(str,x,y);

Note: - public void paint (Graphics g) method is used to refresh to content of frame.

There are 2 ways of creating a color1) We can directly mention the color name from color class.

Ex: - Color.red2) Color c=new Color (r,g,b);

RGB values range 0 to 256

to display a string in the frame import java.awt.*;import java.awt.event.*;class MyMessage extends Frame{

// vars// deafault constructorMyMessage( ){

// write code to close the framethis.addWindowListener(new WindowAdapter()

{public void windowClosing(WindowEvent e){

System.exit(0);}

});} // end of constructor// to refresh the frame contentspublic void paint(Graphics g){

// display the background color in framethis.setBackground(new Color(100,30,30));// set a text colorg.setColor(Color.green);// set a fontFont f=new Font("sansSerif",Font.BOLD +Font.ITALIC ,45);g.setFont(f);// now display the messageg.drawString("HELLOW Sudheer Reddy ! ",100,200);

}public static void main(String[] args) {

// create on obj to frameMyMessage mm=new MyMessage( );

SUDHEER REDDY

44

Page 45: Advanced Java Notes

POTHURAI

// increase the w&hmm.setSize(700,500);// give a title for framemm.setTitle("P.SUDHEER REDDY");// display the framemm.setVisible(true);

}}

D:\psr\Adv java>javac MyMessage.javaD:\psr\Adv java>java MyMessage

Frame: - It is also a componentA frame is a top-level window that does not contain in another window. It is

a container to place the components.

1) To create a frame extends your class to frame class. Then create an object to your class.2) To set a title for the class use setTitle( )3) To set the size of the frame use setSize( )4) To display the frame use setVisible( )5) Refreshing the contents of a frame:

The component class has got a method: paint( ) that paints the area in a frame.

6) Displaying text in a frame:Use Graphics class method: drawString( );

7) Displaying images in a frameUse graphics class method: drawImage( );

About Components: - (components class methods)8) Any component can be added to a frame using add( )9) A component can be removed from a frame using remove( )10) All components can be removed from frame with removeAll( )11) Any component can be displayed using setVisible(true)12) Any component can be disappeared using setVisible(false)13) A components colors can be set using

setBackground( ), setForeground( )14) Font for the displayed text on the component can be with

setFont( )

SUDHEER REDDY

45

Page 46: Advanced Java Notes

POTHURAI

15) A component can be placed in a particular location in the frame with setBounds( )

Creating a font: -Font f=new Font(“name”,style,size);setFont(f); // component class also in graphics class.

Creating color: - 1) setColor(Color.red);2) Color c=new Color(255,0,0); //RGB values

setColor(c);

Maximum sizes of screen in pixels are 800 x 600Listeners: -

A listener is an interface that listens to an event from a component. Listeners are used in java.awt.event.

Component Listener Listener methods1) Button ActionListener actionPerformed (ActionEvent ae)2) Checkbox ItemListener itemStateChanged (ItemEvent ie)3) CheckboxGroup ItemListener 4) Label -----------5)TextField ActionListener focusGained (FocusEvent fe)

Or FocusListener

6)TexrArea ActionListener focusLost (FocusEvent fe) Or

FocusListener7) Choice ItemListener

Or ActionListener

8) List ItemListener Or

ActionListener9) Scrollbar AdjustmentListener adjustmentValueChenged

Or (AdjustmentEvent e) MouseMotionListener mouseDragged(MouseEvent me)

mouseMoved(MouseEvent me)

Note1: - The above listener methods are all ‘public void’ method.Note2: -A listener can be added to a component using addxxxListener( ) Ex: - addActionListener( )Note3: - A listener can be removed from a component using

removexxxListener methodEx: - removeActionListener( )

Note4: - A listener method takes an object of xxxEvent classEx: - actionPerformed(ActionEvent ae)

SUDHEER REDDY

46

Page 47: Advanced Java Notes

POTHURAI

Displaying images in the frame: - To display images in the frame we can use drawImage( ) method of Graphics class.Ex: - g.drawString(image obj,x,y,ImageObserver obj);

f.setIconImage( );

g.drawString( );

// displaying the images in the frame import java.awt.*;import java.awt.event.*;class Images extends Frame{

// varsstatic Image img;// constructorImages( ){

// load the image into img img=Toolkit.getDefaultToolkit( ).getImage("D:/Photo's/Sudheer.jpg");

// create an object media TrackerMediaTracker track=new MediaTracker(this);// add the image to media tracker track.addImage(img,0);// make the JVM wait till img is completely loadedtry{

track.waitForID(0);}catch (InterruptedException ie){

ie.printStackTrace( );}// add window listener to close the framethis.addWindowListener(new WindowAdapter( ){

public void windowClosing(WindowEvent e){

System.exit(0);}

});

SUDHEER REDDY

47

-- [] X

Page 48: Advanced Java Notes

POTHURAI

}public void paint(Graphics g){

// display the imageg.drawImage(img,100,100,null); // (or) g.drawImage(img,100,100,200,200,null);

}public static void main(String[] args) {

// create the frameImages i=new Images( );// set the title & sizei.setTitle("My image");i.setSize(600,500);// display the same image in the title bari.setIconImage(img);// display the framei.setVisible(true);

}}

D:\psr\Adv java>javac Images.javaD:\psr\Adv java>java Images

Button: - Button class is useful to create push buttons. A push button triggers a series of events.

1) To create a push button with a label:Button b=new Button( );

2) To get the label of the button:String l=b.getLabel( );

SUDHEER REDDY

48

Page 49: Advanced Java Notes

POTHURAI

3) To set the label of the button:b.setLabel(“label”);

4) To get the label of the button clicked:String s=ae.getActionCommand( );

// crating push buttons import java.awt.*;import java.awt.event.*;class Mybuttons extends Frame implements ActionListener{

// vars Button b1,b2,b3;// constructorMybuttons( ){

// dont use any layout managerthis.setLayout(null);// create 3 push buttonsb1=new Button("Green");b2=new Button("Red");b3=new Button("Blue");// set the location of buttonsb1.setBounds(50,100,75,40);b2.setBounds(50,170,75,40);b3.setBounds(50,240,75,40);// add the buttons to framethis.add(b1);this.add(b2);this.add(b3);// add actionlistener to buttonsb1.addActionListener(this);b2.addActionListener(this);b3.addActionListener(this);// write code to close the framethis.addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent we){

System.exit(0);}

});}// end of constructorpublic void actionPerformed(ActionEvent ae){

// know which button is clicked by userif(ae.getSource( )==b1)

this.setBackground(Color.green);

SUDHEER REDDY

49

Page 50: Advanced Java Notes

POTHURAI

else if(ae.getSource( )==b2)this.setBackground(Color.red);

else if(ae.getSource( )==b3)this.setBackground(Color.blue);

/* String str=ae.getActionCommand();if(str.equals("Green"))

this.setBackground(Color.green);else if(str.equals("Red"))

this.setBackground(Color.red);else if(str.equals("Blue"))

this.setBackground(Color.blue); */}public static void main(String[] args) {

// create on obj to frameMybuttons mb=new Mybuttons();// set the size & tirlemb.setSize(500,450);mb.setTitle("My fush buttons");// display the framemb.setVisible(true);

}}

D:\psr\Adv java>javac Mybuttons.javaD:\psr\Adv java>java Mybuttons

SUDHEER REDDY

50

Page 51: Advanced Java Notes

POTHURAI

What is the default layout manager in a frame?A) Border layout

What is the default layout manager in applets?A) Flow layout

Checkbox: - A checkbox is a square shaped box which provides a set of options to the user.

1) To create a checkboxCheckbox cb=new Checkbox(“label”);

2) To create a checked CheckboxCheckbox cb=new Checkbox(“label”,null,true);

3) To get the state of a checkboxboolean b=cb.getState( );

4) To set the state of a Checkbox Cb.setState(true);

5) To get the label of a CheckboxString s=cb.getlabel( );

6) To get the selected Checkbox label in to an array we can use getSelectedObjects( );method. This method returns an array of Size 1 only.Object x[ ][ ]=cb.getSelectedObjects( );

Checkbox c1=new Checkbox(“one”); Checkbox c2=new Checkbox(“two”);Object x[ ]=c1.getSelectedObjects( );If(x[0]!=null)g.drawString((String)x[0],x,y);

//creating check boxes import java.awt.*;import java.awt.event.*;class Mycheck extends Frame implements ItemListener{

// varsString str;Checkbox c1,c2,c3;Mycheck( ){

// set the layout manager to flow layoutsetLayout(new FlowLayout (FlowLayout.LEFT));// create 3 check boxesc1=new Checkbox("Bold",null,true);c2=new Checkbox("Italic");c3=new Checkbox("Under line");// add the checkboxes to frame

SUDHEER REDDY

51

Page 52: Advanced Java Notes

POTHURAI

add(c1);add(c2);add(c3);// add item listeners to checkboxc1.addItemListener(this);c2.addItemListener(this);c3.addItemListener(this);// close the frameaddWindowListener(new WindowAdapter( ){public void windowClosing(WindowEvent e){

System.exit(0);}});

}public void itemStateChanged(ItemEvent ie){

// call paint( )repaint( );

}public void paint(Graphics g)

{// display the state of check boxesstr="Bold:"+c1.getState( );g.drawString(str,50,100);str="Italic:"+c2.getState( );g.drawString(str,50,120);str="Under line:"+c3.getState( );g.drawString(str,50,140);

}public static void main(String[] args) {

Mycheck mc=new Mycheck( );// set the size & titlemc.setSize(500,400);mc.setTitle("My cheakBox");// display the framemc.setVisible(true);

}}

D:\psr\Adv java>javac Mycheck.javaD:\psr\Adv java>java Mycheck

SUDHEER REDDY

52

Page 53: Advanced Java Notes

POTHURAI

Repaint methods calls which method?A) Update method it will call internally.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 checkbox group class & checkbox classes.

1) To create a radio buttonCheckboxGroup cbg=new CheckboxGroup( );Checkbox cb=new Checkbox(“label”,cbg,true);

2) To know the selected CheckboxCheckbox cb=cbg.getSelectedCheckbox( );

3) To know the selected Checkbox label:String label=cbg.getSelectedCheckbox( ).getLabel( );

// create radio button import java.awt.*;import java.awt.event.*;class Myradio extends Frame implements ItemListener{

// varsString msg;CheckboxGroup cbg;Checkbox a,b;// construtorMyradio( ){

// set layout manager to flow layoutsetLayout(new FlowLayout( ));// create radio buttonscbg=new CheckboxGroup( );a=new Checkbox("yes",cbg,true);b=new Checkbox("no",cbg,false);// add radio buttons to frameadd(a);add(b);

SUDHEER REDDY

53

Page 54: Advanced Java Notes

POTHURAI

// add item listeners to radio buttonsa.addItemListener(this);b.addItemListener(this);// write code to close the framethis.addWindowListener(new WindowAdapter( ){

public void windowClosing(WindowEvent we){

System.exit(0);}

});}public void itemStateChanged(ItemEvent ie){

repaint( );}public void paint(Graphics g){

// display the atate of redio buttonsmsg="Current selection : ";msg+=cbg.getSelectedCheckbox( ).getLabel();g.drawString(msg,10,100);

}public static void main(String[] args) {

// create a frameMyradio mr=new Myradio( );// set title & sizemr.setTitle("my radio buttons");mr.setSize(500,450);// display framemr.setVisible(true);

}}

D:\psr\Adv java>javac Myradio.javaD:\psr\Adv java>java Myradio

SUDHEER REDDY

54

Page 55: Advanced Java Notes

POTHURAI

Choice menu: - Choice menu is a popup list of items. Only 1 item can be selected.

1) To create a choice menuChoice ch=new Choice( );

2) To add items to the Choice menuCh.add(“text”);

3) To know the name of the selected from the Choice menuString s=ch.getSelectedItem( );

4) To know the index of the currently selected item.int i=ch.getSelectedIndex( );this method returns -1 if nothing is selected.

// create choice boxes import java.awt.*;import java.awt.event.*;class Mychoice extends Frame implements ItemListener{

String msg;Choice ch;Mychoice( ){

// set flow layout managersetLayout(new FlowLayout( ));// create choice menuch=new Choice( );// add items to chch.add("Idly");ch.add("Dosee");ch.add("Ootappam");ch.add("Poori");ch.add("Veg biriyani");// add choice box to frameadd(ch);// add item listeners to Choiceboxch.addItemListener(this);// write code to close the framethis.addWindowListener(new WindowAdapter( ){

public void windowClosing(WindowEvent we){

System.exit(0);}

});}public void itemStateChanged(ItemEvent ie){

repaint( );

SUDHEER REDDY

55

Page 56: Advanced Java Notes

POTHURAI

}public void paint(Graphics g){

// know which method is seletedmsg=ch.getSelectedItem();g.drawString("Your selected : ",50,150);g.drawString(msg,50,170);

}public static void main(String[] args) {

Mychoice mc=new Mychoice( );mc.setTitle("my choice box");mc.setSize(500,450);// display framemc.setVisible(true);

}}

D:\psr\Adv java>javac Mychoice.javaD:\psr\Adv java>java Mychoice

List box: - A list box is similar to a choice box, but it allows the user to select multiple items.

1) To create a list boxList lst=new List( ); // only 1 item can be selected.List lst=new List(3,true); // 3 items are initially visible.

2) To add items to the list boxlst.add(“text”):

3) To get the selected itemsString x[ ]=lst.getSelectedItems( );

4) To get the selected indexesint x[ ]=lst.getSelectedIndexes( );

SUDHEER REDDY

56

Page 57: Advanced Java Notes

POTHURAI

// create list box import java.awt.*;import java.awt.event.*;class Mylist extends Frame implements ItemListener{

String msg[];List ch;Mylist( ){

setLayout(new FlowLayout( ));// create choice menuch=new List(3,true);// add items to chch.add("Uggani");ch.add("Vada");ch.add("Mysoor bajji");ch.add("Noodles");ch.add("Chicken biriyani");// add choice box to frameadd(ch);// add item listeners to Choiceboxch.addItemListener(this);this.addWindowListener(new WindowAdapter( ){

public void windowClosing(WindowEvent we){

System.exit(0);}

});}public void itemStateChanged(ItemEvent ie){

repaint( );}public void paint(Graphics g){

// know which method is seletedmsg=ch.getSelectedItems( );g.drawString("Your selected : ",50,150);for(int i=0;i<msg.length;i++)g.drawString(msg[i],50,170+i*20);

}public static void main(String[] args) {

Mylist ml=new Mylist( );ml.setTitle("my list box");ml.setSize(500,450);

SUDHEER REDDY

57

Page 58: Advanced Java Notes

POTHURAI

ml.setVisible(true);}

}

D:\psr\Adv java>javac Mylist.javaD:\psr\Adv java>java Mylist

Label: - A label is a constant text that is displayed with a text field/text area. It will not perform any task

label

name:

1) To create a label:Label l=new Label(“text”, alignment constants);

Note: - Alignment constants areLabel.RIGHT,Label.LEFT,Label.CENTER.

Text field: - Text field allows a user to enter a single line of text.1) To create a text field

TextField tf=new TextField(25);2) To get the text from TextField

String s=tf.getText( );3) To set the text into a TextField

tf.setText(“text”);4) To hide the text being typed the TextField by a character

tf.setEchoChar(‘char’);

Text area: - Text area is similar to a Text field, but it accept more than one line of text from the user.

SUDHEER REDDY

58

Page 59: Advanced Java Notes

POTHURAI

1) To create a text areaTextArea ta=new TextArea( );TextArea ta=new TextArea(rows,cols);

Note: - TextArea support getText( ) & setText( );

// labels & text fields import java.awt.*;import java.awt.event.*;class Mytext extends Frame implements ActionListener{

Label n,p;TextField name,pass;Mytext( ){

setLayout(new FlowLayout( ));// create teo labelsn=new Label("enter name : ",Label.LEFT);p=new Label("enter password : ",Label.LEFT);// create two text fieldsname=new TextField(20);pass=new TextField(20);// hide the pass word by a '?'pass.setEchoChar('?');// set colorsname.setBackground(Color.blue);name.setForeground(Color.green);name.setFont(new Font("Arial",Font.BOLD,24));// add the components to frameadd(n);add(name);add(p);add(pass);// add action listenername.addActionListener(this);pass.addActionListener(this);// write code to close the framethis.addWindowListener(new WindowAdapter( ){

public void windowClosing(WindowEvent we){

System.exit(0);}

});}public void actionPerformed(ActionEvent ae){

repaint( );

SUDHEER REDDY

59

Page 60: Advanced Java Notes

POTHURAI

}public void paint(Graphics g){

g.drawString("name:"+name.getText( ),20,150);g.drawString("password:"+pass.getText( ),20,170);

}public static void main(String[] args) {

Mytext mt=new Mytext( );mt.setSize(500,450);mt.setTitle("My lable & text fields");mt.setVisible(true);

}}

D:\psr\Adv java>javac Mytext.javaD:\psr\Adv java>java Mytext

Frame1

Frame2 // moving from one frame to another frame import java.awt.*;import java.awt.event.*;

SUDHEER REDDY

60

Back

Next

Page 61: Advanced Java Notes

POTHURAI

class Frame1 extends Frame implements ActionListener{

Button b;Frame1( ){

setLayout(null);// create two labelsb=new Button("Next");b.setBounds(50,100,80,40);add(b);// add action listenerb.addActionListener(this);// write code to close the framethis.addWindowListener(new WindowAdapter( ){

public void windowClosing(WindowEvent we){

System.exit(0);}

});}public void actionPerformed(ActionEvent ae){

// create frame 2 object & displayFrame2 f2=new Frame2(10,"sudheer reddy");f2.setSize(300,300);f2.setVisible(true);

}public static void main(String[] args) {

// create on obj to frameFrame1 f1=new Frame1( );// set size & widthf1.setSize(500,450);f1.setTitle("My lable & text fields");// display the framef1.setVisible(true);

}}

// moving from one frame to another frame import java.awt.*;import java.awt.event.*;class Frame2 extends Frame implements ActionListener{

// varsButton b;

SUDHEER REDDY

61

Page 62: Advanced Java Notes

POTHURAI

int id;String name;Frame2(int i,String s){

id=i;name=s;setLayout(new FlowLayout( ));// create teo labelsb=new Button("Back");add(b);// add action listenerb.addActionListener(this);

}public void actionPerformed(ActionEvent ae){

// dispose frame 2this.dispose( );

}public void paint(Graphics g){

g.drawString("Id ="+id,50,100);g.drawString("name ="+name,50,120);

}}D:\psr\Adv java>javac Frame1.javaD:\psr\Adv java>javac Frame2.javaD:\psr\Adv java>java Frame1

Problems in awt: - Java codeButton b=new Button(“OK”);

C code Pear

SUDHEER REDDY

62

Native methodOK

OK

Page 63: Advanced Java Notes

POTHURAI

Pear component is equivalent component. It is based method.1) When an awt component is created internally it classes a native method (function) which crates a pear component. This pear component is displayed by awt. So awt is called pear component based model. It is depending C code internally.

Windows OS

Linux OS Look=appearance Feel=user interaction

Solaris OS

2) The look & feel of awt components are changing depending upon the operating system. It means portability is not there.3) awt components are heavy weight components. They (use) take more resources of the system. That means they execute slowly, more processor time. Because of the above problems the java.awt package has been re written purely in java.

JFC:-java foundation classes. JFC’s represent class library developed in pure java. It is extension of awt.

awt JFC JFC is an extension of the original awt. It contains libraries that are completely portable. 1) JFC components are light -weight. They take less system resources. 2) JFC components will have same look & feel on all platforms.3) The programmer can change the look & feel as suited for a platform.4) JFC offers a rich set of components with lots of features.5) JFC does mot replace awt. It is an extension to awt.

Major packages in JFC: -

1) javax.swing : - To develop components like buttons, menus. 2) javax.swing.plaf : - To provide a native look & feel to swing components. It is

pluggable.

SUDHEER REDDY

63

Page 64: Advanced Java Notes

POTHURAI

3) java.awt.dnd : - To drag & drop the components & data from 1 place to another place.

4) javax.accessibility : - To provide accessibility of applications to disabled persons.

5) java.awt.geom : - To draw 2d graphics, filling, rotating the shapes, etc. geom means geometrical lines.

javax.swing: - All components in swing follow a model-view-controller architecture.

‘model’ stores the data that defines the state of a button (pushed or not) or text present in a text field. ‘view’ creates the visual representation of the component from the data in the model. ‘controller’ deals with user interaction with the component & modifies the model or the view in response to user action.

view

because clicked some

body

Clicked Received model

controller

Advantages of MVC models: - 1) In MVC, the model & the view are separated; hence it is possible to provide different views from the same model. This is the root concept of plaf.2) We can develop view & model using different technologies. For example view can be developed in java & model can be developed in Oracle.3) We can modify view or model without affecting the other one.

model

controller view

SUDHEER REDDY

64

w=70h=40label=OKbg=redfg=greenstatus=0 1

OK

Page 65: Advanced Java Notes

POTHURAI

Window panes: - A window pane represents an area of a window. It is an object that can

contain other components.Title bar

Frame

pushbutton Window pane

There are 4 window panes: -

Component paneOur Component

Layered paneComponent group

Root pane bg Component

Glass panefg Component

JFrameJFrame class methods: -

1) getContentPane( ) : - Returns an object of Container class.2) getLayeredPane( ) : - Returns an object of JLayered pane class.3) getRootPane( ) : - Returns an object of JRootPane class.4) getGlassPane( ): - Returns an object of Component class.

To go to content pane: - JFrame jf=new JFrame( );Container c=jf.getContentPane( );c.add(b);

Creating a frame in swing: -

1) Create a JFrame objectJFrame obj=new JFrame(“title”);

2) Create a class as a sub class to JFrame & create an object to it.class Myclass extends JFrameMyclass obj=new Myclass( );

SUDHEER REDDY

65

-- [] X

Title -- [] X

Page 66: Advanced Java Notes

POTHURAI

Hierarchy of classes in swing: - Component |-JTabbedPane |-JButton Container---------JComponent-----|-JComboBox |-JLabel |JRadio Window---------JWindow |-JToggelButton----| Button | |-JCheckBox Frame-----------JFrame |-JList |-JMenu<Frame Class> |-JMenuBar <Swing class> |-JMenuItem |-JText Java.awt |-JTextComponent--| Field

Javax.swing |-JText Area

// crate a freme in swing import javax.swing.*;class MyFrameSwing1{

public static void main(String[] args) {

// create an object to JFrameJFrame jf=new JFrame("my Swing Frame");// set the sizejf.setSize(400,400);jf.setVisible(true);

}}

D:\psr\Adv java>javac MyFrameSwing1.javaD:\psr\Adv java>java MyFrameSwing1

(or) // crate a freme in swing import javax.swing.*;class MyFrameSwing2 extends JFrame{

public static void main(String[] args) {

// create an object to JFrameMyFrameSwing2 jf=new MyFrameSwing2( );// set the sizejf.setSize(400,400);jf.setVisible(true);

SUDHEER REDDY

66

Page 67: Advanced Java Notes

POTHURAI

//close the framejf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}}

// crate a freme in swing import java.awt.*;import javax.swing.*;class MyFrameSwing3 extends JFrame{

public static void main(String[] args) {

// create an object to JFrameMyFrameSwing3 jf=new MyFrameSwing3( );// go to the content paneContainer c=jf.getContentPane( );c.setBackground(Color.red);// set the sizejf.setSize(400,400);jf.setVisible(true);//close the framejf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}}

D:\psr\Adv java>javac MyFrameSwing3.javaD:\psr\Adv java>java MyFrameSwing3

JFrame: - It is an extended version of java.awt.FrameCreating a JFrame: - 1) To create a JFrame

JFrame jf=new JFrame( );2) To create a JFrame with the specified title

JFrame jf=new JFrame(“title”);3) Adding components

To add components to JFrame, we should add it to container Container c=jf.getContentPane( );c.add(components); (or)jf.getContentPane( ).add(components);

SUDHEER REDDY

67

Page 68: Advanced Java Notes

POTHURAI

4) Removing componentsTo remove a component use c.remove(component);

5) Setting colors for componentsComponent.setBackground(Color);Component.setForeground(Color);

6) Setting line bordersjavax.swing.border. BorderFactory class is helpful. To set different line

borders

Border bd=BorderFactory.createLineBorder(Color.black,3);

Border bd=BorderFactory.createEtchedBorder( );

Border bd=BorderFactory.createBevelBorder (BevelBorder.LOWERED);Border bd=BorderFactory.createBevelBorder(BevelBorder.RAISED);

Border bd=BorderFactory.createMattelBorder(top,left,bottom,right,Color.red)

Component.setBorder(bd);7) Setting a ToolTip to a component

Component.setToolTipText(“This is a swing component”);8) Setting a shortcut key

A shortcut key (mnemonic) is an underlined character used in menus & buttons. It is used with ALT key to select a an option.

Component.settMnemonic(Char);9) Setting a layout manager

c.setLayout(LayoutManager obj);

// a push button with various types import java.awt.*;import javax.swing.*;import javax.swing.border.*;import java.awt.event.*;class MyButtonSwing1 extends JFrame implements ActionListener{

JButton b;

SUDHEER REDDY

68

OK

OK

OK

OK

Page 69: Advanced Java Notes

POTHURAI

JLabel lbl;MyButtonSwing1( ){

Container c=this.getContentPane( );c.setLayout(new FlowLayout( ));// load an image into Image iconImageIcon ii=new ImageIcon("D:/Photos/Photo's/sudheer/PRAVI 4.jpg");b=new JButton("click me",ii);b.setBackground(Color.green);b.setForeground(Color.yellow);Font f=new Font("Arial",Font.BOLD,35);b.setFont(f);// set border for button

Border bd=BorderFactory.createBevelBorder(BevelBorder.RAISED);b.setBorder(bd);// set the tool tip for buttonb.setToolTipText("i am a strong button");// set a short cut keyb.setMnemonic('l');// add button to content panec.add(b);// crate an empty label & add to clbl=new JLabel( );c.add(lbl);// add action llistener to buttonb.addActionListener(this); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}public static void main(String[] args) {

MyButtonSwing1 mb=new MyButtonSwing1( );mb.setSize(500,500);mb.setTitle("My button");mb.setVisible(true);

}public void actionPerformed(ActionEvent ae){

lbl.setFont(new Font("Impact",Font.PLAIN,40));lbl.setText("Hai I am Sudheer Reddy !!!");

}}

D:\psr\Adv java>javac MyButtonSwing1.javaD:\psr\Adv java>java MyButtonSwing1

SUDHEER REDDY

69

Page 70: Advanced Java Notes

POTHURAI

Creating components in swing: -

Creating Checkbox: - A Checkbox is a squared shaped box, which displays an item or position to the user. The user can select one or more options.

JCheckbox cb1=new JCheckbox(“text”);JCheckbox cb2=new JCheckbox(“text”,true);

Creating Radio buttons: - Radio buttons are round shaped to display an item or a position for the user. The user can select only one item from a group of radio buttons. To create a radio buttons we should use 2 classed.

1) JRadioButton.2) ButtonGroup. JRadioButton rb1=new JRadioButton(“text”); JRadioButton rb2=new JRadioButton(“text”,true);

After creating the Radio button we should informed the JVM, that those radio buttons belongs to same group. ButtonGroup bg = new ButtonGroup ( ); bg.add (rb1); bg.add (rb2);

Creating a text field:- A text field is a rectangular box where the user can enter only one line of text. To create a text field we should use J text field class. JTextField jf = new JTextField (20);

Creating a text area:- A text area is a rectangular box where the user can enter several lines of text. To create a Text area we should use J Text Area class. JTextArea ja = new JTextArea(rows, cols);

SUDHEER REDDY

70

Page 71: Advanced Java Notes

POTHURAI

// creating componets in swing import java.awt.*;import java.awt.event.*;import javax.swing.*;class CheckRadio extends JFrame implements ActionListener{

JCheckBox cb1,cb2;JRadioButton rb1,rb2;JTextArea ta;ButtonGroup bg;String msg=" ";CheckRadio( ){

Container c=this.getContentPane( );c.setLayout(new FlowLayout( ));c.setBackground(Color.gray);//create 2 check boxescb1=new JCheckBox("J2SE",true);cb2=new JCheckBox("J2EE");// create 2 radio buttonsrb1=new JRadioButton("Male",true);rb2=new JRadioButton("Female");// tell the JVM that these buttons belongs to d=same groupbg=new ButtonGroup( );bg.add(rb1);bg.add(rb2);// create a text areata=new JTextArea(5,20);// add the components to content panec.add(cb1);c.add(cb2);c.add(rb1);c.add(rb2);c.add(ta);cb1.addActionListener(this);cb2.addActionListener(this);rb1.addActionListener(this);rb2.addActionListener(this);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}public void actionPerformed(ActionEvent ae){

// know the user seletionif(cb1.getModel( ).isSelected( ))

msg+="J2SE";if(cb2.getModel().isSelected( ))

msg+="J2ME";

SUDHEER REDDY

71

Page 72: Advanced Java Notes

POTHURAI

if(rb1.getModel().isSelected( ))msg+="Male";

else if(rb2.getModel( ).isSelected( ))msg+="Female";

// send user seletion to tata.setText(msg);// refresh msgmsg=" ";

}public static void main(String[] args) {

CheckRadio cr=new CheckRadio( );cr.setSize(400,400);cr.setTitle("My components");cr.setVisible(true);

}} D:\psr\Adv java>javac CheckRadio.javaD:\psr\Adv java>java CheckRadio

JTable:- J Table represents data in the form of a table. The table can have rows of data &column headings.

1) To create a JTable:- JTable tab = new JTable (data, column names); Here, data &columns names can be 20 Array or both can be vector of vectors.2) To create a row using a vector:- Vector row = new Vector ( ); row.add(object); //here object represents a column. row. add( object); 3) To create a Table heading we use get TableHeader ( ) method of J Table class. JTableHeader head = tab. getTableHeader( );

Note: - JTableHeader class is defined in javax.swing.table package

SUDHEER REDDY

72

Page 73: Advanced Java Notes

POTHURAI

// A table with rows & columns import java.awt.*;import java.util.*;import javax.swing.*;import javax.swing.border.*;import javax.swing.table.*;class JTableDemo extends JFrame {

JTableDemo( ){

// create data for the tableVector data=new Vector( );// create a rowVector row=new Vector( );// add columns data to rowrow.add("Sudheer Reddy");row.add("System Analyst");row.add("15,000.00");// add this row to data of tabledata.add(row);// create 2 rowrow=new Vector( );row.add("Latha Reddy");row.add("Programmer");row.add("20,000.50");// add this row to data of tabledata.add(row);// create 3 rowrow=new Vector( );row.add("Shilpa Reddy");row.add("Receptionist");row.add("30,000.90");// add this row to data of tabledata.add(row);// create a row with columns namesVector cols=new Vector( );cols.add("Employee name");cols.add("Designation");cols.add("Salary");// create the frameJTable tab=new JTable(data,cols);// set a border for tabletab.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));// create a table headerJTableHeader head=tab.getTableHeader( );// goto the content pane

SUDHEER REDDY

73

Page 74: Advanced Java Notes

POTHURAI

Container c=getContentPane( );// set border layout to cc.setLayout(new BorderLayout( ));

/* Frame

*/// add the table to cc.add("North",head);c.add("Center",tab);// close the framesetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}public static void main(String[] args) {

// crate the frameJTableDemo jtd=new JTableDemo( );jtd.setSize(500,400);jtd.setTitle("My table");jtd.setVisible(true);

}}

D:\psr\Adv java>javac JTableDemo.javaD:\psr\Adv java>java JTableDemo

JTabbedPane: - It is a container to add multiple components, on every tab. The user can choose a component from a tab.

SUDHEER REDDY

74

-- [] X

North

West Center East

South

Page 75: Advanced Java Notes

POTHURAI

1) To create a JTabbedPaneJTabbedPane jtp=new JTabbedPane( );

2) To add tabsJtp.addTab(“title”,object);

3) To create a panel containing some componentsclass MuPane extends JPanel // now pass MyPane class object to addTab( )

4) To remove a tab & its components from the tabbed panejtp.removeTabAt(int index);

5) To remove all the tabs & their corresponding componentsjtp.removeAll( );

// A table pane with tab sheets import java.awt.*;import javax.swing.*;class JTabbedPaneDemo extends JFrame{

JTablePaneDemo( ){

// create a tabbed paneJTabbedPane jtp=new JTabbedPane( );// add two tab sub sheetsjtp.addTab("Countries",new CountriesPanel( ));jtp.addTab("Capitals",new CapitalsPanel( ));// goto the content paneContainer c=getContentPane( );// add tabbed pane to cc.add(jtp);

}public static void main(String[] args) {

// create the frameJTablePaneDemo jtpd=new JTablePaneDemo( );jtpd.setSize(400,500);jtpd.setTitle("My tabbed pane");jtpd.setVisible(true);// close the frame

jtpd.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}

}class CountriesPanel extends JPanel{

CountriesPanel( ){

JButton b1,b2,b3;b1=new JButton("America");b2=new JButton("India");

SUDHEER REDDY

75

Page 76: Advanced Java Notes

POTHURAI

b3=new JButton("Japan");add(b1);add(b2);add(b3);

}}class CapitalsPanel extends JPanel{

CapitalsPanel( ){

JCheckBox c1,c2,c3;c1=new JCheckBox("Washington");c2=new JCheckBox("Delhi");c3=new JCheckBox("Tokyo");add(c1);add(c2);add(c3);

}}

D:\psr\Adv java>javac JTabbedPaneDemo.javaD:\psr\Adv java>java JTabbedPaneDemo

JSplitPane: - It is used to divide two (& only 2) components.

HORIZONTAL_SPLIT

VERTICAL_SPLIT

1) Creating a JSplit pane:SplitPane sp = new JSplitPane(orientation,components1, components2);

Here: orientation is:JSplitPane.HORIZONTAL_SPLIT to align the components from left to right.

SUDHEER REDDY

76

Page 77: Advanced Java Notes

POTHURAI

JScriptPane.VERTICAL_SPLIT to align the components from top to bottom. 2) Setting the divider location between the components. sp.setDividerLocation(int pixels); 3) Creating the divider location. int n=sp.getDividerLocation( ); 4) To get the top or left side component. Component obj = sp.getTopComponent ( );5) To get the bottom or right side component. Component obj = sp.getBottomComponent ( );6) To remove a component from Split pane. sp.remove(component obj );

Push button

Text area

// A Split pane with two components: import java.awt.*;import java.awt.event.*;import javax.swing.*;class JSplitPaneDemo extends JFrame implements ActionListener{

// varsJSplitPane sp;JButton b;JTextArea ta;String str="This is my text with several lines which is displayed in the text area.This text will be wrapped or not wrapped depending on the settings";JSplitPaneDemo( ){

// goto the content paneContainer c=getContentPane( );// set border layout manager to cc.setLayout(new BorderLayout());// create a push buttonb=new JButton("Click here");// create a text areata=new JTextArea( );// set line wrapping

SUDHEER REDDY

77

Page 78: Advanced Java Notes

POTHURAI

ta.setLineWrap(true); // create a horizontal spilt pane & display the button & text area sp=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,b,ta);

// set the divider location at 300 pxsp.setDividerLocation(300);// add spilt pane to cc.add("Center",sp);// add action listener to buttonb.addActionListener(this);// close the framesetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}public void actionPerformed(ActionEvent ae){

// send text to tata.setText(str);

}public static void main(String[] args) {

// create the freameJSplitPaneDemo jsp=new JSplitPaneDemo( );jsp.setSize(500,400);jsp.setVisible(true);

}}

D:\psr\Adv java>javac JSplitPaneDemo.javaD:\psr\Adv java>java JSplitPaneDemo

Root node 1 level C:\

Psr nodes 2 level java programs

JsplitPane.java 3 level MyClass.java

MyFrame.java

SUDHEER REDDY

78

Page 79: Advanced Java Notes

POTHURAI

Tree structure JTree: - This component displays a set of hierarchical data as an outlineCreating a JTree: -

1) Create nodes of the tree (root node, or node, or leaf) using DefaultMutableTreeNode class.

DefaultMutableTreeNode node=new DefaultMutableTreeNode(“java Programs”);

2) Add the nodes to root node, as:root.add(node);

3) Create the tree by supplying root nodeJTree tree=nre JTree(root);To find path of selected itemTreePath tp=tse.getNewLeadSelectionPath( );To find selected item in the treeObject comp=tp.getLastPathComponent( );To know the path number (this represent the level)int n=tp.getPathCount( );

// creating a tree import java.awt.*;import javax.swing.*; // JTreeimport javax.swing.event.*; // TreeSelectionListenerimport javax.swing.tree.*; // TreePathclass JTreeDemo extends JFrame implements TreeSelectionListener{

JTree tree;DefaultMutableTreeNode root;Container c;JTreeDemo( ){

c=getContentPane( );c.setLayout(new BorderLayout( ));// create a root noderoot=new DefaultMutableTreeNode("C:\\");// create other nodesDefaultMutableTreeNode dir=new

DefaultMutableTreeNode("psr");DefaultMutableTreeNode dir1=new

DefaultMutableTreeNode("Java Programs");DefaultMutableTreeNode file1=new

DefaultMutableTreeNode("JSplitPane.java");DefaultMutableTreeNode file2=new

DefaultMutableTreeNode("MyClass.java");DefaultMutableTreeNode file3=new

DefaultMutableTreeNode("MyFrame.java");// add the nodes to root node

SUDHEER REDDY

79

Page 80: Advanced Java Notes

POTHURAI

root.add(dir);root.add(dir1);dir1.add(file1);dir1.add(file2);dir1.add(file3);// create the treetree=new JTree(root);c.add("North",tree);// add TreeSelectionListener to the treetree.addTreeSelectionListener(this);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}public void valueChanged(TreeSelectionEvent tse){

// know the tree path of selected itemTreePath tp=tse.getNewLeadSelectionPath( );System.out.println("Selecited item path="+tp);// know the selected itemObject comp=tp.getLastPathComponent( );System.out.println("Selected Component="+comp);// know the item level numberint n=tp.getPathCount( );System.out.println("its level number="+n);

}public static void main(String[] args)

{JTreeDemo jtd=new JTreeDemo( );jtd.setSize(500,400);jtd.setVisible(true);

}}D:\psr\Adv java>javac JTreeDemo.javaD:\psr\Adv java>java JTreeDemoSelecited item path=[C:\]Selected Component=C:\its level number=1

SUDHEER REDDY

80

Page 81: Advanced Java Notes

POTHURAI

Menu: - A menu represents a list of items for the user select. Menus are user friendly.

JMenuBar

JMenu

JMenuItem

subMenu

JMenu: - Creating a menu: -

1) Creating a menu barJMenuBar mb=new JMenuBar( );

2) Attach this menu bar to the Containerc.add(mb);

3) Create separate menus to attach to the menu barJMenu file=new JMenu("File");

Note: - here, “File” is title for the menu which appears in the menu bar.4) Attach this menu to the menu bar

mb.add(file);5) Create menu items using JMenuItem or JCheckBoxMenuItem or JRadioButtonMenuItem classes.

JMenuItem op=new JMenuItem("open");6) Attach this menu item to the menu

file.add(op);

Creating a sub menu: -

SUDHEER REDDY

81

-- [] XFile Edit

OpenClose[] Print Font ►

CopyPaste

ArialTimes New Roman

Page 82: Advanced Java Notes

POTHURAI

7) Create a menuJMenu font=new JMenu("Font");

Note: - here, font represents a sub menu to be attached to a menu.8) now attach it to a menu

file.add(font);9) attach menu items to the font sub menu

font.add(obj);

Note: - Obj can be a JMenuItem or JCheckBoxMenuItem or JRadioButtonMenuItem.

// creating a sub menu import java.awt.*;import javax.swing.*;import java.awt.event.*;class MyMenu extends JFrame implements ActionListener{

JMenuBar mb;JMenu file,edit,font;JMenuItem op,cl,cp,pt;JCheckBoxMenuItem pr;Container c;MyMenu( ){

// go to the content panec=getContentPane( );//set border layoutc.setLayout(new BorderLayout( ));// create a manu barmb=new JMenuBar( );// add manu bar to cc.add("North",mb);// create file,edit menusfile=new JMenu("File");edit=new JMenu("Edit");// add menus to menu barmb.add(file);mb.add(edit);// create menu itemsop=new JMenuItem("open");cl=new JMenuItem("close");cp=new JMenuItem("copy");pt=new JMenuItem("paste");// add menu items to file, edit menusfile.add(op);file.add(cl);edit.add(cp);

SUDHEER REDDY

82

Page 83: Advanced Java Notes

POTHURAI

edit.add(pt);// disable close itemcl.setEnabled(false);// create check box as menu itempr=new JCheckBoxMenuItem("print");// add pr to file menufile.add(pr);// add a horizontal line in file menufile.addSeparator( );// create font sub menufont=new JMenu("Font");// add font menu to file menufile.add(font);// add menu items to fontfont.add("Arial");font.add("Times New Roman");// add action listeners to menu itemsop.addActionListener(this);cl.addActionListener(this);cp.addActionListener(this);pt.addActionListener(this);pr.addActionListener(this);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}public void actionPerformed(ActionEvent ae){

// know which menu item the user selectedif(op.isArmed( )) this.openFile( );

// System.out.println("Open selected");if(cl.isArmed( ))

System.out.println("close selected");if(cp.isArmed( ))

System.out.println("copy selected");if(pt.isArmed( ))

System.out.println("paste selected");if(pr.getModel( ).isSelected( ))

System.out.println("Printing on");}public static void main(String[] args) {

MyMenu mm=new MyMenu( );mm.setTitle("My Menu");mm.setSize(500,400);mm.setVisible(true);

}// to open a required filevoid openFile( )

SUDHEER REDDY

83

Page 84: Advanced Java Notes

POTHURAI

{// create an object to JFileChooserJFileChooser fc=new JFileChooser( );// display file open dialog boxint n=fc.showOpenDialog(this);// check if user selection completedif(n==JFileChooser.APPROVE_OPTION)

System.out.println("you selected :"+fc.getSelectedFile( ).getName( ));}

}

D:\psr\Adv java>javac MyMenu.javaD:\psr\Adv java>java MyMenuPrinting on

Layout manager: - It is an interface that arranges the components in a particular fashion (manner).

GridLayout: - It arranges the components in a 2d grid.GridLayout( )GridLayout(int rows,int cols)GridLayout(int rows,int cols,int hgap,int vgap)

Here h means horizontal, v means vertical

// grid layout demo import java.awt.*;import javax.swing.*;class GridLayoutDemo extends JFrame{

GridLayoutDemo( ){

Container c=getContentPane( );JButton b1,b2,b3,b4;

SUDHEER REDDY

84

Page 85: Advanced Java Notes

POTHURAI

GridLayout grid=new GridLayout(2,2,20,10);c.setLayout(grid);b1=new JButton("Button1");b2=new JButton("Button2");b3=new JButton("Button3");b4=new JButton("Button4");c.add(b1);c.add(b2);c.add(b3);c.add(b4);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}public static void main(String[] args) {

GridLayoutDemo gl=new GridLayoutDemo( );gl.setSize(500,400);gl.setVisible(true);

}}D:\psr\Adv java>javac GridLayoutDemo.javaD:\psr\Adv java>java GridLayoutDemo

CardLayout: - It arranges the components in the form of deck of cards.CardLayout( )CardLayout(int hgap,int vgap)

1) To retreve the cards:void first(Container)void last(Container)void next(Container)void previous(Container)

2) To add the elementsadd(“card name”,component)

SUDHEER REDDY

85

Page 86: Advanced Java Notes

POTHURAI

// card layout demo import java.awt.*;import java.awt.event.*;import javax.swing.*;class CardLayoutDemo extends JFrame implements ActionListener{

Container c;CardLayout card;CardLayoutDemo( ){

c=getContentPane( );card=new CardLayout( );c.setLayout(card);JButton b1,b2,b3;b1=new JButton("Button1");b2=new JButton("Button2");b3=new JButton("Button3");c.add("First card",b1);c.add("Second card",b2);c.add("Third card",b3);b1.addActionListener(this);b2.addActionListener(this);b3.addActionListener(this);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}public void actionPerformed(ActionEvent ae){

card.next(c);}public static void main(String[] args) {

CardLayoutDemo cl=new CardLayoutDemo( );cl.setSize(500,400);cl.setVisible(true);

}}

SUDHEER REDDY

86

Page 87: Advanced Java Notes

POTHURAI

D:\psr\Adv java>javac CardLayoutDemo.javaD:\psr\Adv java>java CardLayoutDemo

GridBagLayout: - It specify the components in a grid like fashion, in which some components span more than one row or column.

GridBagLayout( ) To specify constraints for the components, we can use GridBag Constraints class object.

GridBagConstraints( )

gridx, gridy: - Specify the row & column at upper left of the component. X=0 X=1 X=2

Y=0

Y=1

Y=3

grid width, grid height: - Specify the number of columns (for gridwidth) or rows (for gridheight) in the components display area. Default value 0.weightx, weighty: - To specify whether the component can be stretched horizontally or vertically, when resized. Generally weights are specified between 0.0 & 1.0. (0.0 tells that the components size will not change when resized).Anchor: - Used when the component is smaller than its display area to determine where (within the area) to place the component. Valid valus are shown below -------------------------------------------------------------------------------------------------------| FIRST_LINE_START PAGE_START FIRST_LINE_END || || LINE_START CENTER LINE_END || || LAST_LINE_START PAGE_END LAST_LINE_END | -------------------------------------------------------------------------------------------------------fill: - used when the components display area is larger than the components size to determine whether and how to resize the component.Ex: - NONE (default), HORIZONTAL, VERTICAL, BOTH.Insets: - space around the component (external padding), in 4 corners.Ex: - insets(0,0,0,00) //default.ipadx,ipady: - To specify internal padding (width wise or height wise)

SUDHEER REDDY

87

Page 88: Advanced Java Notes

POTHURAI

to be added to the component. Default is 0.

// grid bag layout demo import java.awt.*;import javax.swing.*;class GridBagLayoutDemo extends JFrame{

GridBagLayout gbag;GridBagConstraints cons;GridBagLayoutDemo( ){

Container c=getContentPane( );gbag=new GridBagLayout( );c.setLayout(gbag);cons=new GridBagConstraints( );JButton b1,b2,b3,b4,b5;b1=new JButton("Button1");b2=new JButton("Button2");b3=new JButton("Button3");b4=new JButton("Button4");b5=new JButton("Button5");cons.fill=GridBagConstraints.HORIZONTAL;cons.gridx=0;cons.gridy=0;cons.weightx=0.7;gbag.setConstraints(b1,cons);c.add(b1);cons.gridx=1;cons.gridy=0;gbag.setConstraints(b2,cons);c.add(b2);cons.gridx=2;cons.gridy=0;gbag.setConstraints(b3,cons);c.add(b3);cons.gridx=0;cons.gridy=1;cons.ipady=80; // make before tall

SUDHEER REDDY

88

Button 1 Button 2 Button 3

Button 4

Button 5

Page 89: Advanced Java Notes

POTHURAI

cons.gridwidth=3;gbag.setConstraints(b4,cons);c.add(b4);cons.gridx=1; // aligned with button2cons.gridy=2; // third rowcons.ipady=0;// reset to defaultcons.weighty=1.0; // request any extra vertical apacecons.anchor=GridBagConstraints.PAGE_END; // bottom of spacecons.insets=new Insets(20,5,5,5); // top paddingcons.gridwidth=2; // 2 coloumns widegbag.setConstraints(b5,cons);c.add(b5);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}public static void main(String[] args) {

GridBagLayoutDemo gbl=new GridBagLayoutDemo( );gbl.setSize(500,400);gbl.setVisible(true);

}}

D:\psr\Adv java>javac GridBagLayoutDemo.javaD:\psr\Adv java>java GridBagLayoutDemo

Applet: - An applet is a byte code embedded in a web page or html page.Applet=byte code +html page.

Applets travel on internet from server to the client & they are executed on the client machine.Uses of applets: - 1) an applet is used to provide dynamic nature to a web page.2) Applets are used in creation of animation & games.

SUDHEER REDDY

89

Page 90: Advanced Java Notes

POTHURAI

To create an applet we can use java.applet,Applet class (or) javax.swing.Japplet.The following methods of applet class should be overridden while creating applets.

1) public void init( ): - To initializeThis is the first method which is executed immediately when an applet is

loaded. In this method we initialize the variables & parameters, creating the components etc. this method is executed only once.2) public void start( ): - While applet receives focus

This method executed as long as the applet receives focus. Connecting to files & databases retrieving the data, processing the data & displaying the results should be done in start method.3) public void stop( ): - When applet loses focus

This method is executed when applet loses focus. Closing the files & disconnecting from the database should be done in stop method (clean up operations).Note: - start & stop methods can be executed repeatedly.

4) public void destroy( ): - to terminateThis method is executed while the applet is terminated from memory. Any

code which is to be executed after the applets terminations should be written in this method.Note: - stop ( ) method is always executed before destroy method.

These 4 methods are called applet life cycle.Note: - 1) we can use Graphics components in applets & also public void paint (Graphics g) can be used in applets.2) An applet does not contain public static void main(String args[ ])

Applets are executed at client side browser by a small JVM called applet engine.Text is 2 types. They are 1) linear (searching) text 2) hyper (dynamic) text.Html is a text formatting language. It uses the tag to formatted text. A tag is

a String constant used to apply some format.

// a sample applet import java.awt.*;import java.applet.*;public class MyApp extends Applet{

String str="";public void init( ){

setBackground(Color.green);setForeground(Color.yellow);setFont(new Font("Dialig",Font.BOLD,30));str+="init";

}

SUDHEER REDDY

90

Page 91: Advanced Java Notes

POTHURAI

public void start( ){

str+="start";}public void paint(Graphics g){

str+="paint";g.drawString(str,20,100);

}public void stop( ){

str+="stop";}public void destroy( ){}

}<! This html page contains MyApp applet><html><applet code="MyApp.class" width=500 height=400></applet></html>D:\psr\Adv java>javac MyApp.javaD:\psr\Adv java>appletviewer MyApp.html

// a business from using swing components import java.awt.*;import javax.swing.*;import java.awt.event.*;public class MyFormApplet extends JApplet implements ActionListener{

String str="",str1="",str2="";JLabel lbl,n,a,i;JTextField name;

SUDHEER REDDY

91

Page 92: Advanced Java Notes

POTHURAI

JTextArea addr;JList lst;JButton b1,b2;Object x[];Container c;public void init( ){

// create frame & content paneJFrame jf=new JFrame( );c=jf.getContentPane( );c.setBackground(Color.yellow);c.setLayout(null);jf.setSize(500,400);jf.setTitle("MyFormApplet");jf.setVisible(true);// headinglbl=new JLabel( );lbl.setForeground(Color.red);lbl.setFont(new Font("Dialog",Font.BOLD,32));lbl.setText("POTHURAI ONLINE SHOPPING");lbl.setBounds(200,10,500,40);c.add(lbl);// namen=new JLabel("enter name:",JLabel.LEFT);name=new JTextField(20);n.setBounds(50,60,150,40);name.setBounds(200,60,200,40);c.add(n);c.add(name);// addressa=new JLabel("enter address:",JLabel.LEFT);addr=new JTextArea(6,20);a.setBounds(50,110,150,40);addr.setBounds(200,110,200,150);c.add(a);c.add(addr);// itemsi=new JLabel("select items:",JLabel.LEFT);String data[]={"sarees","T-shirts","shorts","jeans",

"knickers","punjabbies"};lst=new JList(data);i.setBounds(50,270,150,40);lst.setBounds(200,270,200,150);c.add(i);c.add(lst);// push buttonsb1=new JButton("OK");

SUDHEER REDDY

92

Page 93: Advanced Java Notes

POTHURAI

b2=new JButton("Cancle");b1.setBounds(200,450,75,40);b2.setBounds(325,450,75,40);c.add(b1);c.add(b2);// add action listeners to buttonsb1.addActionListener(this);b2.addActionListener(this);

}public void actionPerformed(ActionEvent ae){

// know which button is clickedstr=ae.getActionCommand( );// send user selection to addr text area if ok is clickedif(str.equals("OK")){

str1+=name.getText( )+"\n";str1+=addr.getText( )+"\n";x=lst.getSelectedValues( );for(int i=0;i<x.length;i++)

str2+=(String)x[i]+"\n";addr.setText(str1+str2);str1="";str2="";

}else{

// refresh the form contentsname.setText(" ");addr.setText(" ");lst.clearSelection( );

}}

}<! This html page contains MyFormApplet applet><html><applet code="MyFormApplet.class" width=500 height=400></applet></html>D:\psr\Adv java>javac MyFormApplet.javaD:\psr\Adv java>appletviewer MyFormApplet.html

SUDHEER REDDY

93

Page 94: Advanced Java Notes

POTHURAI

shift +click sequential selection.ctrl +click random selection.

// a simple animation import java.awt.*;import java.applet.*;public class Animate extends Applet{

public void paint(Graphics g){

// load an image in to Image objectImage i=getImage(getDocumentBase( ),"image017.gif");for(int x=0;x<800;x++){

g.drawImage(i,x,100,this);try{

Thread.sleep(20);}catch (InterruptedException ie){}

}}

}<! This html page contains Animate applet><html><applet code="Animate.class" width=500 height=400></applet>

SUDHEER REDDY

94

Page 95: Advanced Java Notes

POTHURAI

</html>

D:\psr\Adv java>javac Animate.javaD:\psr\Adv java>appletviewer Animate.html

Generic types: -1) Generic types represent classes & inter faces in a type-safe manner.

class Myclass {DT x; }Myclass<Float> obj=new Myclass<Float>(x);

2) Generic types act on any data type.3) Generic types are internally declared as sub types of object class type. So they can act on only objects.4) They can not act on primitive data Type.5) Java compiler creates a non- Generic version from a generic class or interface by substituting that actual data type in the place of generic parameter. This is called ‘erasure’.6) We can avoid casting in many classes by using Generic types.7) We can create an object to Generic types parameter.Ex: - class Myclass<T>

T obj=new T( ); // invalid

8) The classes of java.util package have been re-written using these components.Ex: - Stack<E> LinkedList<E> ArrayList<E> Vector<E>

Hashtable<K,V> HashMap<K,V>

9) Creating automatically wrapper classes & storing the primitive data type is called ‘auto boxing’.

// a generic class class Myclass<T>{

T obj;Myclass(T obj)

SUDHEER REDDY

95

Page 96: Advanced Java Notes

POTHURAI

{this.obj=obj;

}T getobj( ){

return obj;}

}class Gen1{

public static void main(String[] args) {

Integer i=55; // new Integer(55)Myclass<Integer> obj=new Myclass<Integer>(i);System.out.println("You stored="+obj.getobj( ));Double d=10.1234; // new Double(10.1234)Myclass<Double> obj1=new Myclass<Double>(d);System.out.println("You stored="+obj1.getobj( ));String s="Sudheer";Myclass<String> obj2=new Myclass<String>(s);System.out.println("You stored="+obj2.getobj( ));

}}

D:\psr\Adv java>javac Gen1.javaD:\psr\Adv java>java Gen1You stored=55You stored=10.1234You stored=Sudheer

// a generic method thst display any array elements class Myclass{

static <T>void display(T[] arr){

for (T i:arr)System.out.println(i);

}}class Gen2{

public static void main(String[] args) {

Integer iarr[]={10,20,30,30};Float farr[]={1.1f,2.2f,3.3f};String sarr[]={"Sudheer","Latha","Siri"};Myclass.display(iarr);

SUDHEER REDDY

96

Page 97: Advanced Java Notes

POTHURAI

Myclass.display(farr);Myclass.display(sarr);

}}

D:\psr\Adv java>javac Gen2.javaD:\psr\Adv java>java Gen2102030301.12.23.3SudheerLathaSiri

/* all classes of java.util package have benn re-written using generic types */ import java.util.*;class HT{

public static void main(String[] args) { /*

// till jdk1.5Hashtable ht=new Hashtable( );ht.put("Sachin",new Integer(120));ht.put("Ganguly",new Integer(145));ht.put("Dravid",new Integer(112));ht.put("Sudheer",new Integer(95));String name="Sudheer";Integer runs=(Integer)ht.get(name);System.out.println(name+"="+runs); */// from jdk1.5 onwordsHashtable<String,Integer> ht=new Hashtable <String, Integer>( );ht.put("Sachin",120);ht.put("Ganguly",145);ht.put("Dravid",112);ht.put("Sudheer",95);String name="Ganguly";Integer runs=ht.get(name);System.out.println(name+"="+runs);

}}D:\psr\Adv java>javac HT.javaD:\psr\Adv java>java HTGanguly=145

SUDHEER REDDY

97

Page 98: Advanced Java Notes

POTHURAI

SUDHEER REDDY

98