Advanced Java Notes

December 1, 2018 | Author: Sudheer Reddy Pothurai | Category: Network Socket, Array Data Structure, Web Server, Computer Network, Port (Computer Networking)
Share Embed Donate


Short Description

Download Advanced Java Notes...

Description

1 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 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 Lists 3) Maps. Maps. 1) Sets Sets:: - A set represents a group of elements. Ex: - Hash set, linked hash set, Tree set. 2) Lists 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. Ex 3) Maps Maps:: - A map stores the elements in the form of key valve pairs. Ex:: - Hash table, Hash map. Ex Array List: List: - It is dynamically glowing array that stores objects. It is not synchronized. Proc Proces essi sing ng

Proc Proces essi sing ng simu simult ltan aneo eous usly ly SUDHEER REDDY

2 POTHURAI

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 list ArrayList arl=new ArrayList( ); // store elements in to arl arl.add("apple"); arl.add("banana"); arl.add("pine apple"); arl.add("grapes"); arl.add("mango"); //display the contents of arl System.out.println("ArrayList = "+arl); // remove some elements from arl arl.remove("apple"); arl.remove(1); // display the contents of arl System.out.println("ArrayList = "+arl); // find no of elements in url System.out.println("size of lists = "+arl.size( )); SUDHEER REDDY

3 POTHURAI

}

}

// retrieve the elements using iterator Iterator it=arl.iterator( ); while(it.hasNext( )) System.out.println(it.next( ));

D:\psr\Adv java>javac ArrayaListDemo.java D:\psr\Adv java>java ArrayaListDemo ArrayaList = [apple, banana, pine apple, grapes, mango] ArrayaList = [banana, grapes, mango] size of lists = 3 banana grapes mango Note: - to extract the events one by one from collection objects we can use only one of  the following 1) Iterator 2) Lis ListIt tIterat erator or 3) Enu num mera eration tion Vectors:: - It is a dynamically growing array that stores objects, but it synchronized. Vectors 1) To crate a vector Vector 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 elements v.add(obj); v.add(2,obj); 4) to retrieve elements v.get(2); 5) To remove elements v.remove( ); To remove all elements v.clear( ); 6) To know the current capacity int n=v.capacity( ); 7) To search for first occurrence of an element in the vector int n=v.indexOf(obj) 8) To search for last occurrence of an element int n=v.lastIndexOf(obj); // a vector with int values SUDHEER REDDY

4 POTHURAI

import java.util.*; class VectorDemo { public static void main(String[] args) { // creating an vector v Vector v=new Vector( ); // take an int type of array x[] int x[]={10,33,45,67,89}; // read from x[] & store into v for(int i=0;ijava VectorDemo 10 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 Hashtable: 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.75 HashTable ht=new HashTable(100); 2) To store key value pair ht.put(“Sunil”, cricket player); 3) To get the value when key is given SUDHEER REDDY

5 POTHURAI

ht.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 keys ht.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 table Hashtable ht=new Hashtable( ); // store player name & score ht.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 & display Enumeration 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 & store Integer score=(Integer)ht.get(name); if(score!=null) { int runs=score.intValue( ); System.out.println(name+" has scored runs "+runs); } else SUDHEER REDDY

6 POTHURAI

{

}

}

}

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

D:\psr\Adv java>javac HashtableDemo.java D:\psr\Adv java>java HashtableDemo Yuvaraj Ganguli Dhoni Sehwag Dravid Sachin Enter player name: Ganguli has scored runs 300 Hash map: 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.75 HashMap hm=new HashMap(100); 2) To store key value pair hm.put(“Sunil”, cricket player); 3) To get the value when key is given hm.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 pairs hm.clear( ); // Hash map with telephone entries import java.io.*; import java.util.*; class HashMapDemo { public static void main(String[] args) throws IOException { // vars HashMap hm=new HashMap( ); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String name,str; long phno; // menu SUDHEER REDDY

7 POTHURAI

}

}

while(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.java D:\psr\Adv java>java HashMapDemo 1. Enter entries into phone book  2. Look up in phone book  1 Enter name: Sunil Enter phone number: 247283 1. Enter entries into phone book  2. Look up in phone book  2 Enter name: Sunil Phone number: 247283 1. Enter entries into phone book  2. Look up in phone book  3 What is the difference between Vector & array list? list? SUDHEER REDDY

8 POTHURAI

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: Note 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: Note 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 StringTokenizer: 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 string String piece=st.nextToken( ); 3) To know if more pieces are remaining boolean x=st.hasMoreTokens( ); 4) To know how many no. of piece are there int 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) { // take a string String str="Sunil Kumar Reddy\ is a nice gentle men\ and genious"; SUDHEER REDDY

9 POTHURAI

}

}

}

// cut str into pieces where space is pound StringTokenizer st=new StringTokenizer(str,"\"); // retrieve tokens & display System.out.println("the Tokens are ::"); while(st.hasMoreTokens( )) { String s=st.nextToken( ); System.out.println(s);

D:\psr\Adv java>javac STDemo.java D:\psr\Adv java>java STDemo Sunil Kumar Reddy is a nice gentle men and 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.DATE Calendar.MONTH Calendar.YEAR  Calendar.HOUR  Calendar.MINUTE Calendar.SECOND 3) Use set ( ) to the set the date or time cl.set(Calendar.MONTH,10); // jan 0 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 calendar Calendar cl=Calendar.getInstance( ); // retrieve data int dd=cl.get(Calendar.DATE); int mm=cl.get(Calendar.MONTH); SUDHEER REDDY

10 POTHURAI

}

}

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

D:\psr\Adv java>javac Cal.java D:\psr\Adv java>java Cal Current date : 28/8/2007 Current time : 11:48:34 Date: - Date class is an also useful to handle Date & time. 1) To create an object to Date class Date 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.L DateFormat.LONG ONG 03 September September 2004 19:43:14 19:43:14 GMT+0.5:30 GMT+0.5:30 DateFor DateFormat mat.FUL .FULL L 03 Septem September ber 20 2004 04 19:43:1 19:43:144 o’ clock clock GMT+0 GMT+05:30 5:30 Dat DateFo eFormat.M .ME EDIUM 03-S 3-Sepep-04 19:43: 43:14 DateFormat.SHORT 03/09/04 19:43 3) Applying format to date object is done by format( ) method. String str=fmt.format(d); // System date & time import java.util.*; SUDHEER REDDY

11 POTHURAI

import java.text.*; class MyDate { public static void main(String[] args) { // create date class obj Date d=new Date( ); // format date & time DateFormat fmt=DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFor mat.SHORT,Locale.US); // apply format to d String s=fmt.format(d); // display formated time & date System.out.println(s); } } D:\psr\Adv java>javac MyDate.java D:\psr\Adv java>java MyDate Aug 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 & bytes 2) 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

BufferedInputStream

ObjectInputStream

DataInputStream

OutputStream

SUDHEER REDDY

12 POTHURAI

FileOut FileOutput putStre Stream am

Filter FilterOut Output putStre Stream am

BufferedOutputStream

Object ObjectOut Output putStre Stream am

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 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) Input InputStreamR StreamReader/Ou eader/OutputSt tputStreamW reamWriter: riter: - They They are are brid bridge ge betwe between en bytes 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

13 POTHURAI

DataInputStream

Keyboard

FileOutputStream

MyFile

System.in // creating a file import java.io.*; class Create1 { public static void main(String[] args) throws IOException { // attach keyboard to dataInputStream DataInputStream dis=new DataInputStream(System.in); // attach my file to FileOutputStream FileOutputStream fout=new FileOutputStream("myfile",true); BufferedOutputStream bout=new BufferedOutputStream(fout,1024); // read data from dis & write into fout char ch; System.out.println("Enter data(@ at end):"); while((ch=(char)dis.read( ))!='@') bout.write(ch); // close the file bout.close( ); } } fout 10 sec 10 sec total 1 1 24 sec 1 1 bout 1 total 1 1 13 sec 10 sec So, we used the bout in the above program. D:\psr\Adv java>javac Create1.java D:\psr\Adv java>java Create1 Enter 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 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. @ SUDHEER REDDY

14 POTHURAI

D:\psr\Adv java>type myfile 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 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

MyFile

Monitor

// to read data from a text file import java.io.*; System.out class Read1 { public static void main(String[] args) throws IOException { try { // accept file name from kayboard BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.print("enter a file name :"); String fname=br.readLine( ); //attach my file to FileInputStream FileInputStream fin=new FileInputStream(fname); BufferedInputStream bin=new BufferedInputStream(fin); // read data from fin & display int ch; while((ch=bin.read( ))!=-1) System.out.print((char)ch); // close the file bin.close( ); } catch(FileNotFoundException fe) { System.out.println("Sorry,file not found"); } } } D:\psr\Adv java>javac Read1.java D:\psr\Adv java>java Read1 SUDHEER REDDY

15 POTHURAI

enter a file name :myfile 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 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 string String str="This is an institute "+"\n I am a student here"; // take a file & attah in to FileWriter FileWriter fw=new FileWriter("textfile"); BufferedWriter bw=new BufferedWriter(fw,1024); // read data from str & write in to fw for(int i=0;ijavac Create2.java D:\psr\Adv java>java Create2 D:\psr\Adv java>type textfile This 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 FileReader FileReader fr=new FileReader("textfile"); BufferedReader br=new BufferedReader(fr); // read data from fr & display int ch; while((ch=br.read( ))!=-1) System.out.print((char)ch); // close the file br.close( ); } SUDHEER REDDY

16 POTHURAI

} D:\psr\Adv java>javac Read2.java D:\psr\Adv java>java Read2 This 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

fis File1

dos

fos 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.java D:\psr\Adv java>edit file1 D:\psr\ Adv java>type file1 Hai i am Sunil Kumar Reddy My pet name is Sudheer Reddy SUDHEER REDDY

17 POTHURAI

… … D:\psr\Adv java>java Compress D:\psr\Adv java>dir file*.* Volume in drive D is DISK  Volume Serial Number is 280A-AE9B Directory of D:\psr\Adv java 08/29/2007 04:48 PM 353 file1 08/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 file2 x£≤H╠T╚TH╠.═╦╠Q≡.═M,JMI⌐Σσ≥¡T(HQ╚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.java D:\psr\Adv java>java UnCompress D:\psr\Adv java>dir file*.* Volume in drive D is DISK  Volume Serial Number is 280A-AE9B Directory of D:\psr\Adv java SUDHEER REDDY

18 POTHURAI

08/29/2007 04:48 PM 353 file1 08/29/2007 04:48 PM 71 file2 08/29/2007 04:54 PM 353 file3 3 File(s) 777 bytes 0 Dir(s) 9,683,546,112 9,683,546,11 2 bytes free D:\psr\Adv java>type file3 Hai i am Sunil Kumar Reddy My 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.

Client Web browser

Server 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. 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. SUDHEER REDDY

19 POTHURAI

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. .com commercial website .edu educational website .mil military 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

0

Network 7

Local Address 24 16,777,216 hosts

class B

10

Network14

Local Address 16 65,536 hosts

class C

110

Network 21

Local Address 8 256 hosts

class 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.

S

C

Socket Port number is an identificati identification on number given to the socket. Every new socket should have a new port number. Establishing communication between server & client: Using a socket is called socket programming. Server socket class: - It is useful to create server side socket Socket class: - It is useful to create client side socket. SUDHEER REDDY

20 POTHURAI

S C // 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 no ServerSocket ss=new ServerSocket(777); // server waits till a connection is accepted by the client System.out.println("Server is waiting......"); Socket s=ss.accept( ); System.out.println("connected to client"); // attach output stream to socket OutputStream obj=s.getOutputStream( ); // to send data till the socket PrintStream ps=new PrintStream(obj); // send data from server String str="Hello Client "; ps.println(str); ps.println("How are you ?"); ps.println("Bye"); // disconnect server ps.close( ); ss.close( ); s.close( ); } } D:\psr\adv java>javac Server1.java

S C // a server that sends message to clients import java.io.*; import java.net.*; class Client1 SUDHEER REDDY

21 POTHURAI

{

}

public static void main(String args[] ) throws Exception { // create client side socket Socket s=new Socket("localhost",777); // add inputstream to the socket InputStream obj=s.getInputStream( ); // to recieve data from socket BufferedReader br=new BufferedReader(new InputStreamReader(obj)); // now receive data String str; while((str=br.readLine( ))!=null) System.out.println(str); // disconnect server s.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 Server is waiting...... connected to client

D:\psr\adv java>java Client1 Hello 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); 6) Read data coming from the client using buffered reader BufferedReader br=new BufferedReader(new InputStreamReader(System.in(obj)); ch=br.read( ); SUDHEER REDDY

22 POTHURAI

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 BR  BufferedReader br=new BufferedReader(new InputStreamReader(System.in(obj)); ch=br.read( ); str=br.readLine( ); Closing communication: - close all streams & sockets ps.close( ); br.close( ); dos.close( ); ss.close( ); s.close( ); 1) local object 2) remote object : - it is an object that is // chat server created another JVM, which is existing on the network. it import java.io.*; can be accessed through references. import java.net.*; class Server2 { public static void main(String[] args) throws Exception { // create ServerSocket ServerSocket ss=new ServerSocket(999); // wait till a client connection accepted Socket s=ss.accept( ); System.out.println("Connection established....."); // send data to client PrintStream ps=new PrintStream(s.getOutputStream( )); // to recive data from client BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream( ))); // to read from keyboard BufferedReader kb=new BufferedReader(new InputStreamReader(System.in)); // communication with client while(true) { SUDHEER REDDY

23 POTHURAI

}

}

}

String str,str1; while((str=br.readLine( ))!=null) { System.out.println(str); str1=kb.readLine( ); ps.println(str1); } //disconnect the Server ps.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 ClientSocket Socket s=new Socket("localhost",999); // send data to Server DataOutputStream dos=new DataOutputStream(s.getOutputStream( )); // to receive data from Server BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream( ))); // to read data from keyboard BufferedReader kb=new BufferedReader(new InputStreamReader(System.in)); // communication with client String str,str1; while(!(str=kb.readLine( )).equals("exit")) { dos.writeBytes(str+"\n"); str1=br.readLine( ); System.out.println(str1); } //disconnect the Server SUDHEER REDDY

24 POTHURAI

}

}

s.close( ); dos.close( ); br.close( ); kb.close( );

D:\psr\adv java>javac Client2.java D:\psr\adv java>java Server2 Connection established..... Hellow! How r u? I am fine. Who r u? I am Usha Rani. What's What's ur name? My name is Sudheer Reddy. Any way I will chat later with u. Bye ra. Smile please OK tom tomorro orrow w I will will meat eat u. Bye. Bye.

D:\psr\adv java>java Client2 Hellow! How r u? I am fine. Who r u? I am Usha Rani. What's ur name? My name is Harinath Harinath Reddy. Any way I will chat later with u. Bye ra. Smile please OK tomorrow I will meat u. Bye. exit 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.java D:\psr\Adv java>java MyClass This 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. 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.

SUDHEER REDDY

25 POTHURAI

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

Tasks 0.25 ms

0.25 ms

0.25 ms

0.25 ms

Round robin: - Executing 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. a)  b)

Process based multi tasking : - Executing several programs at a time is called process based multi tasking. Thread based multi taskin taskingg: - Using multiple threads to execute different blocks of code is called thread based multi tasking. SUDHEER REDDY

26 POTHURAI

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 class public void run( ) { statements; } Note: - Any thread can recognize only run method. A thread executes only the run method. 3) Create an object to class MyClass mc=new MyClass( ); 4) Create a thread & attach to the object Thread t=new Thread(obj); 5) Run the thread t.start( ); // creating a thread import java.io.*; class Myclass extends Thread { public void run( ) { boolean x=false; for(int i=1;ijavac TDemo.java D:\psr\Adv java>java TDemo 1 2 3 4 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 threadi Multi threading: ng: - 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 // invalid But if we write implements Runnable then there is still scope to extends some other class. class MyClass implements Thread,Frame // valid So 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; } public void run( ) { for(int i=1;ijavac TDemo1.java D:\psr\Adv java>java TDemo1 cut Ticket :1 Show Chairs:1 cut Ticket :2 Show Chairs:2 … … cut Ticket :10 Show Chairs:10 // 2 threads acting on same thread class Reserve implements Runnable { int wanted; int available=1; Reserve(int i) { wanted=i; } public void run( ) { SUDHEER REDDY

29 POTHURAI

}

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 class Reserve obj=new Reserve(1); // create 2 Threads & attach them tp obj Thread t1=new Thread(obj); Thread t2=new Thread(obj); // set names to Threads t1.setName("1st person"); t2.setName("2nd Person"); // run the Threads t1.start( ); t2.start( ); } } D:\psr\Adv java>javac Safe.java D:\psr\Adv java>java Safe Available no. of berths = 1 1Berths allotted for 1st person Available no. of berths = 0 SUDHEER REDDY

30 POTHURAI

Sorry, Berths not available Thread synchronization: - When a thread is acting on an object, preventing 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 method Ex: - 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

100 200

Comp

Train Book ticket

// Cancel the ticket class CancleTicket extends Thread { Object train,comp; CancleTicket(Object train,Object comp) { this.train=train; this.comp=comp; SUDHEER REDDY

31 POTHURAI

}

} 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) { } System.out.println("Cancel ticket has to lock compartment...."); synchronized(comp) SUDHEER REDDY

32 POTHURAI

}

}

{ 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 object Object train=new Object( ); Object comp=new Object( ); // create object to Cancle ticket, book ticket CancleTicket obj1=new CancleTicket(train,comp); BookTicket obj2=new BookTicket(train,comp); // create 2 threads & attach to obj's Thread t1=new Thread(obj1); Thread t2=new Thread(obj2); // run the threads t1.start( ); t2.start( ); } } D:\psr\Adv java>javac DeadLock.java D:\psr\Adv java>java DeadLock  Cancel ticket has locked compartment Cancel ticket has locked train Cancel ticket has to lock train.... Cancel ticket has to lock compartment.... There is no solution 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 ( ); 2) To start a thread: t. start ( ); 3) To stop execution or a thread for a specified time: Thread.Sleep(mille seconds); SUDHEER REDDY

33 POTHURAI

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

sb data prod over False Producer

Prod Consumer

// Thread communication: class Communicate { public static void main(String[] args) throws Exception { // create producer & consumer obj's Producer obj1=new Producer( ); Consumer obj2=new Consumer(obj1); // creates threads & attach from obj's Thread t1=new Thread(obj1); SUDHEER REDDY

34 POTHURAI

}

Thread t2=new Thread(obj2); // start the Threads t1.start( ); t2.start( );

} class Producer extends Thread { // to store data StringBuffer sb; // to represent data production over or not // boolean dataprodover=false; Producer( ) { // allot memory to sb sb=new StringBuffer( ); } public void run ( ) { synchronized(sb) { // create 10 items for(int i=1;ijavac Communicate.java D:\psr\Adv java>java Communicate Appending.......... Appending.......... Appending.......... Appending.......... Appending.......... Appending.......... Appending.......... Appending.......... Appending.......... Appending.......... 1:2:3:4:5:6:7:8:9:10: In thre thread ad comm commun unic icat atio ions ns noti notify fy,, noti notify fyAl All,l, wait wait are are used used for for effi effici cien entt communication. Thread group: - A thread group represents a group of threads. 1) Creating a thread group ThreadGroup tg=new ThreadGroup(“group name”); 2) To add a thread to this group tg Thread t1=new Thread(tg, target obj, “thread name”); 3) To add another thread group to this group. ThreadGroup tg1=new ThreadGroup(tg, “group name”); SUDHEER REDDY

36 POTHURAI

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

t1 t2

res

t3 t4

can tg1

// 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 group Thread 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 group Thread 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 tg1 System.out.println("Parent of tg1 = "+tg1.getParent( )); // set mam priority to tg1 as 7 tg1.setMaxPriority(7); // know the thread group of t1 & t3 System.out.println("ThreadGroup of t1 ="+t1.getThreadGroup( )); System.out.println("ThreadGroup of t3 ="+t3.getThreadGroup( )); // start the threads t1.start( ); SUDHEER REDDY

37 POTHURAI

}

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.java D:\psr\Adv java>java WhyTGroup no.of threads in this group = 0 Parent 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 Thread no. of threads in this group = 3 I am a reservation Thread I am a Cancellation Thread I 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. runnable

new thread

start

yield

not runnable SUDHEER REDDY

38 POTHURAI

runnable if run( ) terminates

sleep( ) wait( ) blocked on I / O

dead

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 components like push button, button, Radio button, button, check menus, frames,…. etc

boxes,

Component means graphical representation of an object. Component means push button. Ex: - Button b=new Button (“ok”) TO develop develop GUI programs programs we can use java,awt& java,awt& javax.swing 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 ||Object------------------|||-

FlowLayout BorderLayout 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.  java.awtt package: - awt means abstract window tool kit. That provides a set of classes  java.aw & interfaces to create GUI programs.

SUDHEER REDDY

39 POTHURAI

|- Label |- Button |- Checkbox Object---------Component------------------|- Choice |- List |- Canvas Checkbox 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)

800 600

(600,800)

H

(800,600)

// creating a frame import java.awt.*; class MyFrame1 { public static void main(String[] args) { // create on obj to frame SUDHEER REDDY

40 POTHURAI

}

}

Frame f=new Frame( ); // increase the w&h f.setSize(500,450); // display the frame f.setVisible(true);

D:\psr\Adv java>javac MyFrame1.java D:\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 frame Frame f=new Frame( ); // increase the w&h f.setSize(500,450); // give a title for frame f.setTitle("P.SUDHEER REDDY"); // display the frame f.setVisible(true); } } D:\psr\Adv java>javac MyFrame2.java D:\psr\Adv java>java MyFrame2

Event: - User interaction with a component is called an event.

SUDHEER REDDY

41 POTHURAI

Ex: - Clocking as an event, onmouseover, key pressed in keyboard, right clicking on event, text field, etc. push button

OK 

interfece

call

Listener

call call

m1 m2 m3

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 listener Listener 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 listen listener er to to the the compo component nent.. 2) Implem Implements ents the the methods methods of listener listener interfa interface. ce. It is this model is useful to provide actions for awt components. 3) When the event event is generated generated listener listener will will execute execute one or more 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 frame Frame f=new Frame( ); // increase the w&h f.setSize(500,450); // give a title for frame f.setTitle("P.SUDHEER REDDY"); // display the frame f.setVisible(true); // add window listener to frame f.addWindowListener(new Myclass( )); } } class Myclass implements WindowListener { public void windowActivated(WindowEvent e){ } SUDHEER REDDY

42 POTHURAI

}

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 frame Frame f=new Frame( ); // increase the w&h f.setSize(500,450); // give a title for frame f.setTitle("P.SUDHEER REDDY"); // display the frame f.setVisible(true); // add window listener to frame f.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

43 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 frame Frame f=new Frame( ); // increse the w&h f.setSize(500,450); // give a title for frame f.setTitle("P.SUDHEER REDDY"); // display the frame f.setVisible(true); // add window listener to frame f.addWindowListener(new WindowAdapter( ) { public void windowClosing(WindowEvent e) { System.exit(0); } }); } } The frame is useful to do the following: 1) To disp display lay messag messages es or or Strin Strings gs 2) To disp displa layy imag images es & phot photos os 3) To display display components components like like push buttons, buttons, radio buttons buttons,, menu’s etc…

SUDHEER REDDY

44 POTHURAI

1) Displa Displaying ying a messa message ge 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 color 1) We can directly mention the color name from color class. Ex: - Color.red 2) 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 Frame { // vars // deafault constructor MyMessage( ) { // write code to close the frame this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } // end of constructor // to refresh the frame contents public void paint(Graphics g) { // display the background color in frame this.setBackground(new Color(100,30,30)); // set a text color g.setColor(Color.green); // set a font Font f=new Font("sansSerif",Font.BOLD +Font.ITALIC ,45); g.setFont(f); // now display the message g.drawString("HELLOW Sudheer Reddy ! ",100,200); } public static void main(String[] args) { // create on obj to frame MyMessage mm=new MyMessage( ); SUDHEER REDDY

45 POTHURAI

}

}

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

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

Frame: - It is also a component A 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 frame Use 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 SUDHEER REDDY

46 POTHURAI

setFont( ) 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) setCo setColo lor( r(Co Colo lor.r r.red) ed);; 2) Color Color c=new c=new Color( Color(255,0 255,0,0); ,0); //RGB //RGB valu values es setColor(c); Maximum sizes of screen in pixels are 800 x 600 Listeners: A listener is an interface that listens to an event from a component. Listeners are used in java.awt.event. Component Listener Listener methods 1) 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 FocusListener 7) Choice ItemListener Or ActionListener 8) List ItemListener Or ActionListener 9) Scrollb Scrollbar ar Adjustm AdjustmentL entList istener ener adjust adjustmen mentVa tValue lueChen Chenged ged Or (AdjustmentEvent e) MouseMotionListener mouseDragged(MouseEvent me) mouseMoved(MouseEvent me) Note1: - The above listener methods are all ‘public void’ method. Note2: -A -A listener can be added to a component using addxxxListener( ) Ex: - addActionListener( ) Note3: - A listener can be removed from a component using removexxxListener method Ex: - removeActionListener( ) Note4: - A listener method takes an object of xxxEvent class SUDHEER REDDY

47 POTHURAI

Ex: - actionPerformed(ActionEvent ae) 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( );

-- [] X

g.drawString( );

// displaying the images in the frame import java.awt.*; import java.awt.event.*; class Images extends Frame { // vars static Image img; // constructor Images( ) { // load the image into img img=Toolkit.getDefaultToolkit( ).getImage("D:/Photo's/Sudheer.jpg"); // create an object media Tracker MediaTracker track=new MediaTracker(this); // add the image to media tracker track.addImage(img,0); // make the JVM wait till img is completely loaded try { track.waitForID(0); } catch (InterruptedException ie) { ie.printStackTrace( ); } // add window listener to close the frame this.addWindowListener(new WindowAdapter( ) { public void windowClosing(WindowEvent e) { System.exit(0); } SUDHEER REDDY

48 POTHURAI

});

}

} public void paint(Graphics g) { // display the image g.drawImage(img,100,100,null); // (or) g.drawImage(img,100,100,200,200,null); } public static void main(String[] args) { // create the frame Images i=new Images( ); // set the title & size i.setTitle("My image"); i.setSize(600,500); // display the same image in the title bar i.setIconImage(img); // display the frame i.setVisible(true); }

D:\psr\Adv java>javac Images.java D:\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: SUDHEER REDDY

49 POTHURAI

String l=b.getLabel( ); 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 implements ActionListener { // vars Button b1,b2,b3; // constructor Mybuttons( ) { // dont use any layout manager this.setLayout(null); // create 3 push buttons b1=new Button("Green"); b2=new Button("Red"); b3=new Button("Blue"); // set the location of buttons b1.setBounds(50,100,75,40); b2.setBounds(50,170,75,40); b3.setBounds(50,240,75,40); // add the buttons to frame this.add(b1); this.add(b2); this.add(b3); // add actionlistener to buttons b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); // write code to close the frame this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); }// end of constructor public void actionPerformed(ActionEvent ae) { // know which button is clicked by user if(ae.getSource( )==b1) SUDHEER REDDY

50 POTHURAI

this.setBackground(Color.green); 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 frame Mybuttons mb=new Mybuttons(); // set the size & tirle mb.setSize(500,450); mb.setTitle("My fush buttons"); // display the frame mb.setVisible(true); }

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

SUDHEER REDDY

51 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 checkbox Checkbox cb=new Checkbox(“label”); 2) To create a checked Checkbox Checkbox cb=new Checkbox(“label”,null,true); 3) To get the state of a checkbox boolean b=cb.getState( ); 4) To set the state of a Checkbox Cb.setState(true); 5) To get the label of a Checkbox String 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 implements ItemListener { // vars String str; Checkbox c1,c2,c3; Mycheck( ) { // set the layout manager to flow layout setLayout(new FlowLayout (FlowLayout.LEFT)); // create 3 check boxes c1=new Checkbox("Bold",null,true); c2=new Checkbox("Italic"); c3=new Checkbox("Under line"); // add the checkboxes to frame SUDHEER REDDY

52 POTHURAI

add(c1); add(c2); add(c3); // add item listeners to checkbox c1.addItemListener(this); c2.addItemListener(this); c3.addItemListener(this); // close the frame addWindowListener(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 boxes str="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 & title mc.setSize(500,400); mc.setTitle("My cheakBox"); // display the frame mc.setVisible(true); }

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

SUDHEER REDDY

53 POTHURAI

Repaint methods calls which method? A) Update method it will call internally. Radio buttons: - A radio button represents represents a round shaped button, such that only one can be selected from a panel. Radio button button can be created using checkbox checkbox group class & checkbox classes. 1) To create a radio button CheckboxGroup cbg=new CheckboxGroup( ); Checkbox cb=new Checkbox(“label”,cbg,true); 2) To know the selected Checkbox Checkbox 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 implements ItemListener { // vars String msg; CheckboxGroup cbg; Checkbox a,b; // construtor Myradio( ) { // set layout manager to flow layout setLayout(new FlowLayout( )); // create radio buttons cbg=new CheckboxGroup( ); a=new Checkbox("yes",cbg,true); b=new Checkbox("no",cbg,false); // add radio buttons to frame add(a); add(b); SUDHEER REDDY

54 POTHURAI

// add item listeners to radio buttons a.addItemListener(this); b.addItemListener(this); // write code to close the frame this.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 buttons msg="Current selection : "; msg+=cbg.getSelectedCheckbox( ).getLabel(); g.drawString(msg,10,100); } public static void main(String[] args) { // create a frame Myradio mr=new Myradio( ); // set title & size mr.setTitle("my radio buttons"); mr.setSize(500,450); // display frame mr.setVisible(true); }

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

SUDHEER REDDY

55 POTHURAI

Choice menu: - Choice menu is a popup list of items. Only 1 item can be selected. 1) To create a choice menu Choice ch=new Choice( ); 2) To add items to the Choice menu Ch.add(“text”); 3) To know the name of the selected from the Choice menu String s=ch.getSelectedItem( ); 4) To know the index of the 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 manager setLayout(new FlowLayout( )); // create choice menu ch=new Choice( ); // add items to ch ch.add("Idly"); ch.add("Dosee"); ch.add("Ootappam"); ch.add("Poori"); ch.add("Veg biriyani"); // add choice box to frame add(ch); // add item listeners to Choicebox ch.addItemListener(this); // write code to close the frame this.addWindowListener(new WindowAdapter( ) { public void windowClosing(WindowEvent we) { System.exit(0); } }); } public void itemStateChanged(ItemEvent ie) { repaint( ); SUDHEER REDDY

56 POTHURAI

}

} public void paint(Graphics g) { // know which method is seleted msg=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 frame mc.setVisible(true); }

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

List box: - A list box is similar to a choice box, but it allows the user to select multiple multiple items. 1) To create a list box List 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 box lst.add(“text”): 3) To get the selected items String x[ ]=lst.getSelectedItems( ); 4) To get the selected indexes int x[ ]=lst.getSelectedIndexes( ); SUDHEER REDDY

57 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 menu ch=new List(3,true); // add items to ch ch.add("Uggani"); ch.add("Vada"); ch.add("Mysoor bajji"); ch.add("Noodles"); ch.add("Chicken biriyani"); // add choice box to frame add(ch); // add item listeners to Choicebox ch.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 seleted msg=ch.getSelectedItems( ); g.drawString("Your selected : ",50,150); for(int i=0;ijavac Mylist.java D:\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 are Label.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

59 POTHURAI

1) To create a text area TextArea 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 labels n=new Label("enter name : ",Label.LEFT); p=new Label("enter password : ",Label.LEFT); // create two text fields name=new TextField(20); pass=new TextField(20); // hide the pass word by a '?' pass.setEchoChar('?'); // set colors name.setBackground(Color.blue); name.setForeground(Color.green); name.setFont(new Font("Arial",Font.BOLD,24)); // add the components to frame add(n); add(name); add(p); add(pass); // add action listener name.addActionListener(this); pass.addActionListener(this); // write code to close the frame this.addWindowListener(new WindowAdapter( ) { public void windowClosing(WindowEvent we) { System.exit(0); } }); } public void actionPerformed(ActionEvent ae) { repaint( ); SUDHEER REDDY

60 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.java D:\psr\Adv java>java Mytext

Next Back 

Frame1

Frame2

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

SUDHEER REDDY

61 POTHURAI

{

}

Button b; Frame1( ) { setLayout(null); // create two labels b=new Button("Next"); b.setBounds(50,100,80,40); add(b); // add action listener b.addActionListener(this); // write code to close the frame this.addWindowListener(new WindowAdapter( ) { public void windowClosing(WindowEvent we) { System.exit(0); } }); } public void actionPerformed(ActionEvent ae) { // create frame 2 object & display Frame2 f2=new Frame2(10,"sudheer reddy"); f2.setSize(300,300); f2.setVisible(true); } public static void main(String[] args) { // create on obj to frame Frame1 f1=new Frame1( ); // set size & width f1.setSize(500,450); f1.setTitle("My lable & text fields"); // display the frame f1.setVisible(true); }

// moving from one frame to another frame import java.awt.*; import java.awt.event.*; class Frame2 extends Frame implements implements ActionListener { // vars Button b; int id; SUDHEER REDDY

62 POTHURAI

String name; Frame2(int i,String s) { id=i; name=s; setLayout(new FlowLayout( )); // create teo labels b=new Button("Back"); add(b); // add action listener b.addActionListener(this); } public void actionPerformed(ActionEvent ae) { // dispose frame 2 this.dispose( ); } public void paint(Graphics g) { g.drawString("Id ="+id,50,100); g.drawString("name ="+name,50,120); }

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

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

Native method

Java code

OK  C code

OK 

Pear

Pear component is equivalent component. It is based method. SUDHEER REDDY

63 POTHURAI

1) Wh When en an awt awt comp compon onent ent is crea created ted inter interna nallllyy it clas classe sess a nati native ve meth method od (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 Solaris OS

Look=appearance Feel=user interaction

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  java foundati foundation on classes. 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) 2)

 javax.swing: - To develop components like buttons, menus.  javax.swing  javax.swing.p  javax. swing.plaf laf: - To provide a native look & feel to swing components. It is pluggable. SUDHEER REDDY

64 POTHURAI 3) 4) 5)

 java.awt.dnd: - To drag & drop the components & data from 1 place to  java.awt.dnd another place.  javax.accessib  javax.a ccessibility ility: - To provi provide de acces accessi sibi bilility ty of appli applica cati tion onss to disa disabl bled ed persons.  java.awt.geom  java.a wt.geom: - To draw 2d graphics, filling, rotating the shapes, etc. geom means geometrical lines.

 javax.swing:  javax.s wing: 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.

w=70 h=40 label=OK  bg=red fg=green status=0 1

view

OK  Clicked

Received

because clicked some body

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

65 POTHURAI

Window panes: A window pane represents an area of a window. It is an object that can contain other components. Title bar Frame

-- [] X push button

Window pane

There are 4 window panes: Component pane Our Component Layered pane Component group

Title

-- [] X

Root pane bg Component Glass pane fg Component

JFrame

JFrame class methods: 1) getContentPane( ) : - Returns an object of Container class. class. 2) getLayeredPane( ) : - Returns an object of JLayered pane class. 3) getRootPane( ) : - Returns an object of JRootPane class. getGlassPane sPane(( ): - Returns an object of Component class. 4) getGlas 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 object JFrame obj=new JFrame(“title”); 2) Create a class as a sub class to JFrame & create an object to it. class Myclass extends JFrame Myclass obj=new Myclass( ); SUDHEER REDDY

66 POTHURAI

Hierarchy of classes in swing: Component

|- JTabbedPane |- JButton Container---Container---- -----JComp -----JComponent--onent-----|--|- JComboBox |- JLabel | JRadio Window---------JWindow |- JToggelButton----| Button | |- JCheckBox Frame-----------JFrame |- JList |- JMenu |- JMenuBar |- 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 JFrame JFrame jf=new JFrame("my Swing Frame"); // set the size  jf.setSize(40  jf.setSize(400,400); 0,400);  jf.setVisi  jf.setVisible(true) ble(true);; } } D:\psr\Adv java>javac MyFrameSwing1.java D:\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 JFrame MyFrameSwing2 jf=new MyFrameSwing2( ); // set the size  jf.setSize(40  jf.setSize(400,400); 0,400); SUDHEER REDDY

67 POTHURAI

}

}

 jf.setVisi  jf.setVisible(true) ble(true);; //close the frame  jf.setDefaul  jf.setDefaultCloseO tCloseOperatio peration(JFram n(JFrame.EXIT e.EXIT_ON_CL _ON_CLOSE); OSE);

// 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 JFrame MyFrameSwing3 jf=new MyFrameSwing3( ); // go to the content pane Container c=jf.getContentPane( ); c.setBackground(Color.red); // set the size  jf.setSize(40  jf.setSize(400,400); 0,400);  jf.setVisi  jf.setVisible(true) ble(true);; //close the frame  jf.setDefaul  jf.setDefaultCloseO tCloseOperatio peration(JFram n(JFrame.EXIT e.EXIT_ON_CL _ON_CLOSE); OSE); } } D:\psr\Adv java>javac MyFrameSwing3.java D:\psr\Adv java>java MyFrameSwing3

JFrame: - It is an extended version of java.awt.Frame Creating 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) SUDHEER REDDY

68 POTHURAI

 jf.getConten  jf.getContentPane( tPane( ).add(co ).add(component mponents); s); 4) Removing components To remove a component use c.remove(component); 5) Setting colors for components Component.setBackground(Color); Component.setForeground(Color); 6) Setting line borders  javax.swing.b  javax.swing.border. order. BorderFactory BorderFactory class is helpful. helpful. To set different different line borders Border bd=BorderFactory.createLineBorder(Color.black,3);

OK  Border bd=BorderFactory.createEtchedBorder( );

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

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

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 { SUDHEER REDDY

69 POTHURAI

}

JButton b; JLabel lbl; MyButtonSwing1( ) { Container c=this.getContentPane( ); c.setLayout(new FlowLayout( )); // load an image into Image icon ImageIcon 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 button b.setToolTipText("i am a strong button"); // set a short cut key b.setMnemonic('l'); // add button to content pane c.add(b); // crate an empty label & add to c lbl=new JLabel( ); c.add(lbl); // add action llistener to button b.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.java D:\psr\Adv java>java MyButtonSwing1

SUDHEER REDDY

70 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 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) JRad JRadio ioBu Butt tton on.. 2) Butto uttonG nGro roup up.. 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

71 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 boxes cb1=new JCheckBox("J2SE",true); cb2=new JCheckBox("J2EE"); // create 2 radio buttons rb1=new JRadioButton("Male",true); rb2=new JRadioButton("Female"); // tell the JVM that these buttons belongs to d=same group bg=new ButtonGroup( ); bg.add(rb1); bg.add(rb2); // create a text area ta=new JTextArea(5,20); // add the components to content pane c.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 seletion if(cb1.getModel( ).isSelected( )) msg+="J2SE"; if(cb2.getModel().isSelected( )) msg+="J2ME"; SUDHEER REDDY

72 POTHURAI

if(rb1.getModel().isSelected( )) msg+="Male"; else else if(r if(rb2 b2.g .get etMo Mode del( l( ).is ).isSe Sele lect cted ed(( )) )) msg+="Female"; // send user seletion to ta ta.setText(msg); // refresh msg msg=" ";

} 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.java D:\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

73 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 JFrame { JTableDemo( ) { // create data for the table Vector data=new Vector( ); // create a row Vector row=new Vector( ); // add columns data to row row.add("Sudheer Reddy"); row.add("System Analyst"); row.add("15,000.00"); // add this row to data of table data.add(row); // create 2 row row=new Vector( ); row.add("Latha Reddy"); row.add("Programmer"); row.add("20,000.50"); // add this row to data of table data.add(row); // create 3 row row=new Vector( ); row.add("Shilpa Reddy"); row.add("Receptionist"); row.add("30,000.90"); // add this row to data of table data.add(row); // create a row with columns names Vector cols=new Vector( ); cols.add("Employee name"); cols.add("Designation"); cols.add("Salary"); // create the frame JTable tab=new JTable(data,cols); // set a border for table tab.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWER  ED)); // create a table header JTableHeader head=tab.getTableHeader( ); // goto the content pane SUDHEER REDDY

74 POTHURAI

/*

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

-- [] X

Frame

North West

Center

East

South */

}

// add the table to c c.add("North",head); c.add("Center",tab); // close the frame setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

} public static void main(String[] args) { // crate the frame JTableDemo jtd=new JTableDemo( );  jtd.setSize(500  jtd.setSize(500,400); ,400);  jtd.setTitle(  jtd.setTitle("My "My table"); table");  jtd.setVisi  jtd.setVisible(tru ble(true); e); }

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

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

75 POTHURAI

1) To create a JTabbedPane JTabbedPane jtp=new JTabbedPane( ); 2) To add tabs Jtp.addTab(“title”,object); 3) To create a panel containing some components class MuPane extends JPanel // now pass MyPane class object to addTab( ) 4) To remove a tab & its components from the tabbed pane  jtp.removeTab  jtp.removeTabAt(int At(int index); 5) To remove all the tabs & their corresponding components  jtp.removeAll  jtp.removeAll(( ); // A table pane with tab sheets import java.awt.*; import javax.swing.*; class JTabbedPaneDemo extends JFrame { JTablePaneDemo( ) { // create a tabbed pane JTabbedPane jtp=new JTabbedPane( ); // add two tab sub sheets  jtp.addTab("C  jtp.addTab("Countri ountries",new es",new Countri CountriesPanel esPanel(( ));  jtp.addTab("C  jtp.addTab("Capital apitals",new s",new Capitals CapitalsPanel( Panel( )); )); // goto the content pane Container c=getContentPane( ); // add tabbed pane to c c.add(jtp); } public static void main(String[] args) { // create the frame JTablePaneDemo jtpd=new JTablePaneDemo( );  jtpd.setSize(4  jtpd.setSize(400,500) 00,500);;  jtpd.setTitl  jtpd.setTitle("My e("My tabbed tabbed pane"); pane");  jtpd.setVis  jtpd.setVisible(tr ible(true); ue); // close the frame  jtpd.setDefa  jtpd.setDefaultClo ultCloseOperat seOperation(JFr ion(JFrame.EX ame.EXIT_ON_ IT_ON_CLOSE CLOSE); ); } } class CountriesPanel extends JPanel { CountriesPanel( ) { JButton b1,b2,b3; b1=new JButton("America"); b2=new JButton("India"); b3=new JButton("Japan"); SUDHEER REDDY

76 POTHURAI

}

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.java D:\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. JScriptPane.VERTICAL_SPLIT to align the components from top to bottom. SUDHEER REDDY

77 POTHURAI

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 implements ActionListener { // vars JSplitPane 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 pane Container c=getContentPane( ); // set border layout manager to c c.setLayout(new BorderLayout()); // create a push button b=new JButton("Click here"); // create a text area ta=new JTextArea( ); // set line wrapping ta.setLineWrap(true); SUDHEER REDDY

78 POTHURAI

// create a horizontal spilt pane & display the button & text area sp=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,b,ta); // set the divider location at 300 px sp.setDividerLocation(300); // add spilt pane to c c.add("Center",sp); // add action listener to button b.addActionListener(this); // close the frame setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

} public void actionPerformed(ActionEvent ae) { // send text to ta ta.setText(str); } public static void main(String[] args) { // create the freame JSplitPaneDemo jsp=new JSplitPaneDemo( );  jsp.setSize(500  jsp.setSize(500,400); ,400);  jsp.setVisib  jsp.setVisible(true) le(true);; }

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

1 level C:\ 2 level 3 level

Root node Psr java programs

nodes

JsplitPane.java MyClass.java MyFrame.java Tree structure SUDHEER REDDY

79 POTHURAI

JTree: - This component displays a set of hierarchical data as an outline Creating 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 node JTree tree=nre JTree(root); To find path of selected item TreePath tp=tse.getNewLeadSelectionPath( ); To find selected item in the tree Object 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.*; // JTree import javax.swing.event.*; // TreeSelectionListener import javax.swing.tree.*; // TreePath class JTreeDemo extends JFrame implements implements TreeSelectionListener { JTree tree; DefaultMutableTreeNode root; Container c; JTreeDemo( ) { c=getContentPane( ); c.setLayout(new BorderLayout( )); // create a root node root=new DefaultMutableTreeNode("C:\\"); // create other nodes DefaultMutableTreeNode 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 root.add(dir); SUDHEER REDDY

80 POTHURAI

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

} public void valueChanged(TreeSelectionEvent tse) { // know the tree path of selected item TreePath tp=tse.getNewLeadSelectionPath( ); System.out.println("Selecited item path="+tp); // know the selected item Object comp=tp.getLastPathComponent( ); System.out.println("Selected Component="+comp); // know the item level number int n=tp.getPathCount( ); System.out.println("its level number="+n); } public static void main(String[] args) { JTreeDemo jtd=new JTreeDemo( );  jtd.setSize(500  jtd.setSize(500,400); ,400);  jtd.setVisib  jtd.setVisible(true) le(true);; }

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

SUDHEER REDDY

81 POTHURAI

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

File

Edit

-- [] X

Open Copy Close Paste [] Print Font ► Arial Times New Roman

JMenu: Creating a menu: 1) Creating a menu bar JMenuBar mb=new JMenuBar( ); 2) Attach this menu bar to the Container c.add(mb); 3) Create separate menus to attach to the menu bar JMenu 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) Creat eate menu enu items ems using JMenu enuItem or JCh JCheck eckBoxMenu enuItem or JRadioButtonMenuItem classes. JMenuItem op=new JMenuItem("open"); 6) Attach this menu item to the menu file.add(op); Creating a sub menu: 7) Create a menu JMenu 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 SUDHEER REDDY

82 POTHURAI

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 pane c=getContentPane( ); //set border layout c.setLayout(new BorderLayout( )); // create a manu bar mb=new JMenuBar( ); // add manu bar to c c.add("North",mb); // create file,edit menus file=new JMenu("File"); edit=new JMenu("Edit"); // add menus to menu bar mb.add(file); mb.add(edit); // create menu items op=new JMenuItem("open"); cl=new JMenuItem("close"); cp=new JMenuItem("copy"); pt=new JMenuItem("paste"); // add menu items to file, edit menus file.add(op); file.add(cl); edit.add(cp); edit.add(pt); // disable close item cl.setEnabled(false); // create check box as menu item pr=new JCheckBoxMenuItem("print"); // add pr to file menu file.add(pr); // add a horizontal line in file menu file.addSeparator( ); // create font sub menu font=new JMenu("Font"); // add font menu to file menu SUDHEER REDDY

83 POTHURAI

file.add(font); // add menu items to font font.add("Arial"); font.add("Times New Roman"); // add action listeners to menu items op.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 selected if(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 file void openFile( ) { // create an object to JFileChooser JFileChooser fc=new JFileChooser( ); // display file open dialog box int n=fc.showOpenDialog(this); // check if user selection completed if(n==JFileChooser.APPROVE_OPTION) System.out.println("you selected :"+fc.getSelectedFile( ).getName( )); }

D:\psr\Adv java>javac MyMenu.java SUDHEER REDDY

84 POTHURAI

D:\psr\Adv java>java MyMenu Printing 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; 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); } SUDHEER REDDY

85 POTHURAI

public static void main(String[] args) { GridLayoutDemo gl=new GridLayoutDemo( ); gl.setSize(500,400); gl.setVisible(true); }

} D:\psr\Adv java>javac GridLayoutDemo.java D:\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 elements add(“card name”,component)

SUDHEER REDDY

86 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); } } D:\psr\Adv java>javac CardLayoutDemo.java D:\psr\Adv java>java CardLayoutDemo

SUDHEER REDDY

87 POTHURAI

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= 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 ------------------------------------------------------------------------------------------------------| FIRS FIRST_ T_LI LINE NE_S _STA TART RT PAGE PAGE_S _STA TART RT FIRS FIRST_ T_LI LINE NE_E _END ND | | | | 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) to be added to the component. Default is 0.

Button 1

Button 2

Button 3

Button 4 Button 5 SUDHEER REDDY

88 POTHURAI

// grid bag layout demo import java.awt.*; import javax.swing.*; class GridBagLayoutDemo extends JFrame 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 cons.gridwidth=3; gbag.setConstraints(b4,cons); c.add(b4); cons.gridx=1; cons.gridx=1; // aligned aligned with button2 button2 cons.gridy=2; cons.gridy=2; // third third row row cons.ipady=0; cons.ipady=0; // reset to default default cons cons.w .weig eight hty= y=1.0 1.0;; // req reques uestt any any eext xtra ra verti vertica call apac apacee cons.an con s.ancho chor=G r=GridB ridBagC agCons onstrai traints nts.PA .PAGE_ GE_END END;; // bottom bottom of spa space ce cons cons.in .inset sets= s=new new Inset Insets( s(20 20,5, ,5,5,5 5,5); ); // top top pad paddin dingg cons cons.g .gri ridw dwid idth th=2 =2;; // 2 col colou oumn mnss wid widee gbag.setConstraints(b5,cons); SUDHEER REDDY

89 POTHURAI

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.java D:\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. To create an applet we can use java.applet,Applet class (or)  javax.swing.Ja  javax.swing.Japplet.T pplet.The he following methods methods of applet class class should be overridden while while creating applets. 1) public void init( ): - To initialize This is the first method which is executed immediately when an applet is loade loaded. d. In this this meth method od we init initia ialilize ze the the varia variabl bles es & param paramet eters ers,, creat creating ing the 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. SUDHEER REDDY

90 POTHURAI

3) public void stop( ): - When applet loses focus This This metho ethodd is exec execut uted ed when when appl applet et lose losess focu focus. s. Clos Closin ingg the the file filess & 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 terminate This 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"; } 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( ) SUDHEER REDDY

91 POTHURAI

{ }

} D:\psr\Adv java>javac MyApp.java D:\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; JTextArea addr; JList lst; JButton b1,b2; Object x[]; Container c; public void init( ) { // create frame & content pane JFrame jf=new JFrame( ); c=jf.getContentPane( ); c.setBackground(Color.yellow); c.setLayout(null);  jf.setSize(50  jf.setSize(500,400); 0,400);  jf.setTitle(  jf.setTitle("MyFo "MyFormApp rmApplet"); let"); SUDHEER REDDY

92 POTHURAI

 jf.setVisi  jf.setVisible(true) ble(true);; // heading lbl=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); // name n=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); // address a=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); // items i=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 buttons b1=new JButton("OK"); 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 buttons b1.addActionListener(this); b2.addActionListener(this);

} public void actionPerformed(ActionEvent ae) { // know which button is clicked str=ae.getActionCommand( ); // send user selection to addr text area if ok is clicked

SUDHEER REDDY

93 POTHURAI

}

if(str.equals("OK")) { str1+=name.getText( )+"\n"; str1+=addr.getText( )+"\n"; x=lst.getSelectedValues( ); for(int i=0;i D:\psr\Adv java>javac MyFormApplet.java D:\psr\Adv java>appletviewer MyFormApplet.html

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

94 POTHURAI

// 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 object Image i=getImage(getDocumentBase( ),"image017.gif"); for(int x=0;x D:\psr\Adv java>javac Animate.java D:\psr\Adv java>appletviewer Animate.html

Generic types: 1) Generic types represent classes & inter faces in a type-safe manner. class Myclass { DT x; } SUDHEER REDDY

95 POTHURAI

Myclass obj=new Myclass(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 obj=new T( ); // invalid 8) The classes of java.util package have been re-written using these components. Ex: - Stack LinkedList ArrayListVector Hashtable HashMap 9) Creating automatically wrapper classes & storing the primitive data type is called ‘auto boxing’. // a generic class class Myclass { T obj; Myclass(T obj) { this.obj=obj; } T getobj( ) { return obj; } } class Gen1 { public static void main(String[] args) { Integer Integer i=55 i=55;; // new new Integ Integer(5 er(55) 5) Myclass obj=new Myclass(i); System.out.println("You stored="+obj.getobj( )); Doub Double le d=1 d=10. 0.123 1234; 4; // new new Dou Doubl ble(1 e(10. 0.123 1234) 4) Myclass obj1=new Myclass(d); System.out.println("You stored="+obj1.getobj( )); String s="Sudheer"; Myclass obj2=new Myclass(s); System.out.println("You stored="+obj2.getobj( )); } SUDHEER REDDY

96 POTHURAI

} D:\psr\Adv java>javac Gen1.java D:\psr\Adv java>java Gen1 You stored=55 You stored=10.1234 You stored=Sudheer // a generic method thst display any array elements class Myclass { static 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); Myclass.display(farr); Myclass.display(sarr); } } D:\psr\Adv java>javac Gen2.java D:\psr\Adv java>java Gen2 10 20 30 30 1.1 2.2 3.3 Sudheer Latha Siri /* all classes of java.util package have benn re-written using generic types */ import java.util.*; class HT { SUDHEER REDDY

97 POTHURAI

public static void main(String[] args) { /* // till jdk1.5 Hashtable 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.o em.ouut.print rintln ln((na nam me+" e+"="+runs); */ // from jdk1.5 onwords Hashtable ht=new Hashtable ( ); 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.java D:\psr\Adv java>java HT Ganguly=145

SUDHEER REDDY

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF