Advanced Java Material Download From
Advanced Java Material Download From
ADVANCED JAVA
A group of elements are handled by representing with an array.
A group of objects are also handled with array.
To store objects in Array
Employee arr[ ] = new Employee[100];
for(int i = 0; i<100; i++)
{
arr[ i ] = new Employee(……);
}
Java.util Package
Collections class
Collections obj
Collections object (or) Container Object: - It is an object that stores a group other
objects.
Collections class (or) Container class: - It is a class whose object can store other
objects.
All collection classes have defined in java.util package.
Frame work means group of classes.
Which of the collection class will not allow duplicate values? *****
Ans: - Sets of the collection class will not allow the duplicate values. Set will not
stores the object in ordered/sorted order.
Lists of the collection class will allow the duplicate values. List will stores the object
in ordered/sorted order.
1. Set ArrayList
2. List Vector
3. Map LinedList
4. SortedSet HashSet
5. SortedMap TreeSet
6. Iterator Collections
7. ListIterator LinkedHashSet
8. Enumeration HashMap
9. TreeMap
10. HashTable
11. LinkedHashMap
1
Synchronized: - It means only one process will allow to act on one object.
Iterator ListIterator
remove() methods.
2. Access the collections in the forward 2. Access the collections in forward and
direction only. backward directions.
Iterator Enumeration
v.clear();
6. To know the current capacity, use capacity() method
int n = v.capacity();
7. To search for last occurrence of an element use indexOf() method
int n = v . intdexOf(obj);
8. To search for last occurrence of an element use lastIndexOf() method
int n = v . lastIndexOf(obj);
9. Increases the capacity of this vector, if necessary, to ensure that it can hold at
least the number of components specified by the minimum capacity argument.
void ensureCapacity(int minCapacity);
ArrayList is not synchronized by default, but by using some methods we can
synchronized the ArrayList.
List myList = Collections.synchronizedList(myList);
Vector is synchronized default.
When we are retreiveing the elements from Vector, it will maintains and gives
the same order what we have added the elements to the Vector.
Vector doesn’t supports the null values.
Ex: - //A Vector of int values
import java.util.*;
class VectorDemo
{
public static void main(String args[ ])
{
//Create an empty Vector
Vector v = new Vector ();
//Take (an one dimensional) int type array
int x [ ] = {10, 22, 33, 44, 60, 100};
//Read int values from x and store into v
for(int i = 0; i< x.lenght(); i++)
v.add(new Integer(x[ i ]));
//Retrieve and display the elements
for(int i = 0; i< v.size(); i++)
System.out.println(v.get(i));
//Retrieve elements using ListIterator
ArrayList Vector
5. ArrayList doesn’t supports the legacy 5. Vector supports the legacy methods
methods. like hasMoreElements(), nextElement().
Maps: - A map represents storage of elements in the form of the key and value
pairs. Keys must be unique and keys cannot allow duplicate values.
HashTable: - Hashtable stores object in the form of keys and value pairs. It is
synchronized.
1. To create a HashTable
HashTable ht = new HashTable(); //Initial
Capacity = 11, load factor = 0.75
HashTable ht = new HashTable(100);
System.out.println(ht.get("3"));
System.out.println(ht.get("0"));
Enumeration e=ht.elements();
while(e.hasMoreElements()){
System.out.println("---Retreving the elements using enumeration from HashTable =
"+e.nextElement());
}
Enumeration e1=ht.keys();
while(e1.hasMoreElements()){
System.out.println("---Retreving the keys using enumeration from HashTable
= "+e1.nextElement());
}
}
}
O/P: -
---Retreiveing the elements--- = {3=Mogili, 2=Anand, 1=Babu, 0=@Marlabs}
Babu
Anand
Mogili
@Marlabs
---Retreving the elements using enumeration from HashTable = Mogili
---Retreving the elements using enumeration from HashTable = Anand
---Retreving the elements using enumeration from HashTable = Babu
---Retreving the elements using enumeration from HashTable = @Marlabs
---Retreving the keys using enumeration from HashTable = 3
---Retreving the keys using enumeration from HashTable = 2
---Retreving the keys using enumeration from HashTable = 1
---Retreving the keys using enumeration from HashTable = 0
Ex 3: -
import java.util.*;
public class DemoHashTable {
public static void main(String[] args) {
Hashtable ht=new Hashtable();
ht.put("1", "Babu");
HashMap HashTable
1. It stores the objects in the form of key 1. It stores the objects in the form of key
and value pairs. and value pairs.
8. HapMap takes only one null key and 8. HashTable doesn’t takes null keys
many null values. and null values.
String s1 = st.nextToken();
System.out.println(s1);
}
}
}
Form
Name
Server
Address
Section
Name
Ok
DateFormat.SHORT, Locale.US);
Note: -
----------------------------------------------------------------------------------------------------------------
formatconst Example (region = LocaleUK)
----------------------------------------------------------------------------------------------------------------
DateFormat.LONG 03 September 2004 19:43:14 GMT + 5.30
DateFormat.FULL 03 September 2004 19:43:14 oclock GMT + 5.30
DateFormat.MEDIUM 03-Sep-04 19:43:14
DateFormat.LONG 03/09/04 7.43 pm
----------------------------------------------------------------------------------------------------------------
3. Applying format to Date object is done by format () method.
String str = fmtt.format(d);
Ex: - //To display system date and time
import java.util.*;
import java.text.*;
class MyDate
{
public static void main(String args[ ])
{
//Create an obj to Date class
Date d = new Date();
//Store the format in DateFormat obj
DateFormat fmt = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
DateFormat.SHORT, Locale.UK);
//Applying the format to d
String s = fmt.format(d);
//Display the formatted date and time
System.out.println(“System date and time: ”+s);
}
}
Θ Here d represents the system date & time already consists after creating an object.
H.W.
1. Create an Employee class with an employee’s id, name, and address store
objects of this class in an ArrayList. When an employee’s ID is given, display his
name and address.
2. Create a vector with a group of strings. Sort them and display them in a ascending
order. Display them in reverse order also?
3. Create HashTable with some students hall tickets no.’s & their results. Type a hall
ticket number and display his result?
4. Cut the string into pairs of pieces: “India=>Delhi, America=>Washington,
Britain=>London, France=>Paris”
Now display the token as given below.
City Capital
Delhi India
Washington America
London Britain
Paris France
STREAMS: - A stream represents flow of data from one place to another place.
They are two types of streams,
1. Input Streams: - It receives or reads the data to output stream.
2. Output Stream: - It sends or writes the data to some other place.
Streams are represented by classes in java.io package.
Streams (java.io): - A stream is a sequence of bytes, or characters traveling from
source to a destination.
When the bytes passing then it is called as byte stream and when the
characters are passing then it is called as character stream.
To handle data in the form of ‘bytes’, the abstract class: InputStream and
OutputStream are used.
InputStream
|
----------------------------------------------------------------------
| | |
FileInputStream FilterInputStream ObjectInputStream
|
-----------------------------------------
| |
BufferedInputStream DataInputStream
OutputStream
|
-----------------------------------------------------------------------
| | |
FileOutputStream FilterOutputStream ObjectOutputStream
|
-----------------------------------------
| |
BufferedOutputStream DataOutputStream
Reader
|
-----------------------------------------------------------------------------------------------
| | | |
BufferedReader CharArrayReader IntputStreamReader PrintReader
|
FileReader
Writer
|
-----------------------------------------------------------------------------------------------
| | | |
BufferedWriter CharArrayWriter IntputStreamWriter PrintWriter
|
FileWriter
ByteStream stores the data in the form of bytes, CharacterStream stores the
data in the form of characters.
Buffered means a block of memory.
a) BufferedReader/BufferedWriter: - Handles character (text) by buffering them.
They provide efficiency.
b) CharArrayReader/CharArrayWriter: - Handles array of characters.
c) InputStreamReader/OutputStreamWriter: - They are bridge between byte
streams and character streams. Reader reads bytes and then decode them into 16-
bit Unicode character, write decodes character into bytes and then write.
d) PrinterReader/PrinterWriter: - Handle printing of characters on the screen.
A file is an organized collection of data.
How can you improve Java I/O performance:
Java applications that utilise Input/Output are excellent candidates for
performance tuning. Profiling of Java applications that handle significant volumes of
data will show significant time spent in I/O operations. This means substantial gains
can be had from I/O performance tuning. Therefore, I/O efficiency should be a high
priority for developers looking to optimally increase performance. The basic rules for
speeding up I/O performance are:
Minimise accessing the hard disk.
Minimise accessing the underlying operating system.
Minimise processing bytes and characters individually.
Let us look at some of the techniques to improve I/O performance.
Use buffering to minimise disk access and underlying operating system. As
shown below, with buffering
large chunks of a file are read from a disk and then accessed a byte or character at a
time.
Without buffering : inefficient code
try{
File f = new File("myFile.txt");
FileInputStream fis = new FileInputStream(f);
int count = 0;
int b = ;
while((b = fis.read()) != -1){
if(b== '\n') {
count++;
}
}
// fis should be closed in a finally block.
fis.close() ;
}
catch(IOException io){}
Note: fis.read() is a native method call to the underlying system.
With Buffering: yields better performance
try{
File f = new File("myFile.txt");
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
int count = 0;
int b = ;
while((b = bis.read()) != -1){
if(b== '\n') {
count++;
}
}
//bis should be closed in a finally block.
bis.close() ;
}
catch(IOException io){}
Note: bis.read() takes the next byte from the input buffer and only rarely access the
underlying operating system.
Instead of reading a character or a byte at a time, the above code with
buffering can be improved further by reading one line at a time as shown below:
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
DataInputStream FillOutputStrea
m
System.in myfile
import java.io.*;
class Create1
{
public static void main(String args[ ])
throws IOException
{
//Attach the keyboard to DataInputStream
DataInputStream dis = new DataInputStream(System.in);
//Connect file to FileOutputStream
FileOutputStream fout = new FileOutputStream(“myfile”, true);
//reading data from DataInputStream and write that data into FileOutputStream
char ch;
System.out.println(“Enter data (@at end): ”);
while((ch = char) dis.read()) != ‘@’)
fout.write(ch);
//close the file
fout.close();
}
}
To improve the efficiency or the speed of execution of program we to use
Buffered class.
BufferedOutputStream bos = new BufferedOutputStream(fout, 1024);
Default size used by any Buffered class is 512 bytes.
In the place of fout.write(); we have to use bos.write(); and in the place of
fout.close(); we have to use bos.close();
Ex: - //Creating a file
import java.io.*;
class Create1
{
public static void main(String args[ ])
throws IOException
{
//Attach the keyboard to DataInputStream
DataInputStream dis = new DataInputStream(System.in);
throws IOException
{
BufferedInputStream bin = new BufferedInputStream(fin);
//Attach the file to FileInputStream
FileInputStream fin = new FileInputStream(“myfile”);
//now read from FileInputStream and display
int ch;
while((ch = bin.read()) != -1)
System.out.println((char)ch);
//close the file
bin.close();
}
}
Ex: - //Reading data from a text file
import java.io.*;
class Read1
{
public static void main(String args[ ])
throws IOException
{
try{
//to enter filename from keyboard
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.ot.print(“Enter file name: ”);
String fname = readLine();
//Attach the file to FileInputStream
FileInputStream fin = new FileInputStream(fname);
//now read from FileInputStream and display
int ch;
while((ch = bin.read()) != -1)
System.out.println((char)ch);
//close the file
bin.close();
}
catch(FileNotFoundException fe)
{
System.out.println(“File not found”);
}
}
Ex: - //Creating a file
import java.io.*;
class Create2
{
public static void main(String args[ ])
throws IOException
{
//to write data into file
FileWriter fw = new FileWriter(“myfile1.txt”);
//take string
String str = “This is an institute” + “\nIam a student here”;
//read char by char from str and write into fw
for(int i = 0; i<str.length(); i++)
fw.write(str.charAt(i));
//close the file
fw.close();
}
}
Ex: - //Creating a file
import java.io.*;
class Create3
{
public static void main(String args[ ])
throws IOException
{
//to write data into file
FileWriter fw = new FileWriter(“myfile1.txt”);
BufferedWriter bw = new BufferedWriter(fw, 1024);
//take string
{
//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 and write into dos
int data;
while((data = fis.read()) != -1)
dos.write(data);
//close the files
fis.close();
dos.close();
}
}
Here we have to create file1 using Ms-Dos Edit command save it and then
execute the java file.
Ex: - //UnZip
dos
import java.util.*; Writing Writing
import java.util.zip.*; here here
iis
class UnCompress File 2 File 3
java.net package contains classes to create a socket for server and client.
Socket is a class to create a Socket client side.
ServerSocket is a class to create a Socket server side.
These two classes are in java.net package.
{ Socket
class Client1
{
public static void main(String args)
throws Exception
{
//Create Client Socket
Socket s= new Socket(ipaddress/”loacalhost”, 777);
//attach InputStream to Socket
InputStream obj = s.getInputStream();
//To receive the data to this Socket
BufferedReader br = new BufferedReader(new InputStreamReader(obj));
//Accept data coming from Server
String str;
while(str=br.readLine()) !=null)
System.out.println(str);
//Disconnect the Server
s.close();
br.close();
}
}
We can run as many JVM’s at a time.
Communicating from the Server: -
1. Create a ServerSocket
ServerSocket ss = new ServerSocket(Port No.);
2. Accept any Client
Socket s = ss.accept(); ------ It returns Socket object.
3. To send data, connect the OutputStream to the Socket
OutputStream obj = s.getOutputStream();
4. To receive data from the Client, connect InputStream to the Socket
InputStream obj = s.getInputStream();
5. Send data to the Client using PrintStream
Ex: - PrintStream ps = new PrintStream(obj);
ps.print(str);
ps.println(str);
throws Exception
{
//Create Server Socket Reference Object
ServerSocket ss= new ServerSocket(888);
//make this Socket wait for Client connection
Socket s = ss.accept();
System.out.println(“Connection Established”);
//to send data to the Client
PrintStream ps = new PrintStream(s.getOutputStream());
//to receive data from Client
BufferedReader br = new BufferedReader(newInputStreamReader (s.getInputStream()));
//to read data from Keyboard
BufferedReader kb=new BufferedReader(new InputStreamReader(System.in()));
//now communicate
while(true) // Server runs continuously
{
String str, str1;
while(str = br.readLine() != null)
{
System.out.println(str);
str1 = kb.readLine();
ps.println(str1);
}
//Disconnect the Server
ss.close();
s.close();
ps.close();
br.close();
kb.close();
System.exit(0);
}
}
}
Ex: - //Chat Client
import java.io.*;
import java.net.*;
class Client2
{
public static void main(String args)
throws Exception
{
//Create Client Socket
Socket s= new Socket(“Localhost”, 888);
//to send data to the Server
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
//to receive data from Server
BufferedReader br=new BufferedReader(new InputStream(s.getInputStream()));
//to read data from Keyboard
BufferedReader kb=new BufferedReader(new InputStreamReader(System.in()));
//now start communicate
String str, str1;
while(str = br.readLine() .equals(“exit”))
//As long as the String are not typing exit.
{
dos.writeBytes(str+”\n”);
str1 = br.readLine();
System.out.println(str1);
}
//Disconnect the Server
s.close();
dos.close();
br.close();
kb.close();
}
}
H. W.
8. Develop a server that sends to system data and time to the client display that data
and time at client side (Hint: Use Port No.13)
9. Write client server programs so that the client sends the name of a file to the
server and the server sends the file content to client display the file contents at client
side (the file should present in the
server). ----------
Thread: - A thread represents a process ---------- JVM
---------- or
of execution (or) executing the set of
Microprocessor
statements is called a thread. Statements
Every java program is executed by using one thread i.e. is called main thread.
JVM will execute statements step by step.
Microprocessor
Memory
Task
0.25ms 0.25ms 0.25ms 0.25ms
Microprocessor will allot equal timings (0.25milli
seconds) for each task.
Thread class, runnable implements will helpful to create a thread. These two
are available in java.lang package.
2. Write public void run in the class thread will execute only this method.
public void run()
Thread can’t act upon any method, but default it works only on run() method.
3. Create an object to the class.
4. Attach a thread to this object.
5. Start thread, then will act upon that object.
Ex: - //Creating thread
Class MyThread extend Thread
{
public void run()
{
for(int i = 1; i<100000; i++)
{
System.out.println(i);
}
}
}
class TDemo
{
public static void main(String args[ ])
{
MyThread obj = new MyThread();
Thread t1 = new Thread();
t1.start();
}
}
stop() method is used to stop the thread in old versions. But stop() method is
deprecated in new versions.
Forcibly to terminate the program we have to use “control + c” (Ctrl+c keys in
the keyboard).
To stop the thread also we have to use control + c keys.
{
public static void main(String args[ ])
{
//create objects to MyThread class
MyThread obj1=new MyThread(“Cut ticket”);
MyThread obj2=new MyThread(“Show ticket”);
//Create two threads and attach them to //these two objects
Thread t1 = new Thread(obj1);
Thread t2 = new Thread(obj2);
//start the thread
t1.start();
t2.start();
}
}
When multiple threads are acting on the one or same object we will get
sometimes unreliable results.
Ex: - //Two threads acting on one object
class Reserve implements Runnable
{ 2nd thread
st
int available = 1; 1 thread
int wanted;
-------------------
Reserve (int i) -
{ -------------------
-------------------
wanted = i; -
} -------------------
object
public void run() Synchronization
{
System.out.println(“Number of berths available = ”+available);
if(available >= wanted)
{
String name = Thread.currentThread.getName();
System.out.println(wanted + “berths reserved for”+name);
try{
Thread.sleep(2000);
{
wanted = i;
}
public void run()
synchronized(obj)
{
System.out.println(“Number of berths available = ”+available);
if(available >= wanted)
{
String name = Thread.currentThread.getName();
System.out.println(wanted + “berths reserved for”+name);
try{
Thread.sleep(2000);
available = available – wanted;
}
catch(Interrupted Exception ie){ }
}
else
System.out.println(“Sorry, no berths to reserve”);
}
}
}
class Syn
{
public static void main(String args[ ])
{
//create an obj to Reserve class with 1 berth
Reserve obj = new Reserve(1);
//create 2 threads and attach them to obj
Thread t1 = new Thread(obj);
Thread t2 = new Thread(obj);
//give names to threads
t1.setName(“First Person”);
t2.setName(“Second Person”);
}
2. By making a method as synchronized method
synchronized void method()
{ For entire method to synchronized we will use
statements; this method.
}
Ex: - class MethodLevel {
//shared among threads
SharedResource x, y ;
pubic void synchronized
method1() {
//multiple threads can't access
}
pubic void synchronized
method2() {
//multiple threads can't access
}
public void method3() {
//not synchronized
//multiple threads can access
}
}
Synchronization important: - Without synchronization, it is possible for one thread
to modify a shared object while another thread is in the process of using or updating
that object’s value. This often causes dirty data and leads to significant errors.
Disadvantage of synchronization is that it can cause deadlocks when two threads
are waiting on each other to do something. Also synchronized code has the
overhead of acquiring lock, which can adversely the performance.
Synchronization is also known as thread safe, unsynchronized is also known
as thread unsafe.
Locking means it will not allow another thread still the completion of one task
of one thread.
Ex: - //To cancel the ticket
Class CancelTicket extends Thread
{
object train, comp;
CancelTicket(object train, object comp)
Thread 1 CancelTicket
{
this.train = train; 100ms comp.obj
this.comp = comp;
}
public void run()
200ms train.obj
{
synchronized(comp) BookTicket
Thread 2
{
System.out.println(“CancelTicket locked the compartment”);
try{
sleep(100);
}catch(InterruptedException ie){ }
System.out.println(“CancelTicket wants to lock on train”);
synchronized(train)
{
System.out.println(“CancelTicket now locked train”);
}
}
}
}
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(“BookTicket locked the train”);
try{
sleep(200);
}catch(InterruptedException ie){ }
System.out.println(“BookTicket wants to lock on compartmet”);
synchronized(comp)
{
System.out.println(“BookTicket now locked compartment”);
}
}
}
}
class DeadLock
{
public static void main(String args[ ])
throws Exception
{
//take train and compartment as objects
object train = new object();
object compartment = new object();
//create objects to CancelTicket, BookTicket
CancelTicket obj1 = new CancelTicket(train, compartment);
BookTicket obj1 = new BookTicket (train, compartment);
//create 2 threads and attach them to these objects
Thread t1 = new Thread(obj1);
Thread t2 = new Thread(obj2);
//run the threads
t1.start();
t2.start();
}
}
Save it as DeadLock.java compile & run the program.
Output: -
100ms comp.obj
Page 53 of 148 rambabumandalapu@yahoo.com
200ms train.obj
Advanced Java
{
sleep(10);
}
}catch(Exception e){ }
System.out.println(prob.sb);
}
}
Save it as communication.java. This above program/method is not efficient
way to communication between threads.
If we want communicate efficient way we have to use notify() method.
Ex: - //Thread communication in efficient way
Class Communicate
{
public static void main(String args[ ])
{
//create Producer, Consumer, objects
Producer obj1 = new Producer();
Consumer obj2 = new Consumer(obj1);
//create 2 threads and attach them obj1, obj2
Thread t1 = new Thread(obj1);
Thread t2 = new Thread(obj2);
//run the threads
t1.start();
t2.start();
}
}
class Producer extends Thread
{ 1
2 Data Provider
SrtingBuffer sb; true
3
producer() -
-
{
-
sb = new StringBuffer(); 10
}
Producer Consumer
}
}
What is the difference between sleep() method and wait() method? *****
Ans: - Both methods will make the thread wait for some time. When the thread
comes out of sleep() method the object may be still lock. When the threads comes
out of the wait() method the object is automatically unlocked.
But both methods will wait temporarily.
Ex: - synchronized(obj) synchronized(obj)
{ {
---------------------- ----------------------
locked locked
---------------------- ----------------------
sleep(2000); wait(2000);
---------------------- ----------------------
locked Unlocked
---------------------- ----------------------
} }
Running
Yield
Start
New Thread Not Runnable
Runnable
sleep()
The run method terminates
wait()
Dead/Terminates Dead blocked on I/O
(or)
Runnable means it will executes public void run methods yield makes pausing
the thread.
Not Runnable means thread will stop runnable.
Afetr executing the all methods by run() method then the thread will be
terminated.
Runnable: - Waiting for its turn to be picked for execution by the thread schedular
based on thread priorities.
Running: - The processor is actively executing the thread code. It runs until it
becomes blocked, or voluntarily gives up its turn with this static method
Thread.yield(). Because of context switching overhead, yield() should not be used
very frequently.
Waiting: - A thread is in a blocked state while it waits for some external processing
such as file I/O to finish.
Sleeping: - Java threads are forcibly put to sleep (suspended) with this overloaded
method: Thread.sleep(milliseconds), Thread.sleep(milliseconds, nanoseconds);
Blocked on I/O: Will move to runnable after I/O condition like reading bytes of data
etc changes.
Blocked on synchronization: Will move to Runnable when a lock is acquired.
Dead: The thread is finished working.
- - - Checkbox
|
- - - Choice
|
Object- - -Component- - - - - - - List
| |
CheckBoxGroup - - - Canvas
|
- - - Scrollbar - - - TextFiled
|
- - - TextComponent - - -
|
- - - Container - - - TextArea
Panel Window
Applet Frame
Layout manager is an interface that arranges the components on the screen.
Layout manager is implemented in the following classes.
- - - FlowLayout
|
- - - BorderLayout
|
Object - - - - - - - - GridLayout
|
- - - CardLayout
|
- - - GridBagLayout
A frame is a top level window that is not contained in another window.
A window represents the some rectangular part on the screen.
Pixel is a short form of a picture each dot (.) is a pixel. Pixel means picture
element.
Creating a frame: -
1. Create an object to frame class.
Ex: - Frame f = new Frame();
2. Write a class that extends a frame and then creates an object to that class.
Ex: - class MyFrame extends Frame
MyFrame f = new MyFrame(); (x, y)
(0, 0) (800, 0)
This is advantageous than 1st method.
Ex: - //creating a frame
*(400, 300)
import java.awt.*;
* (10, 500)
class MyFrame
{ (0, 600) (800, 600)
public static void main(String args[ ])
{
//create an object to Frame class
Frame f = new Frame();
//increase the size of frame
f.setSize(400,300);
//display the frame
f.setVisible(true); (or) f.show();
}
}
Components are to display but not to perform any task.
Ex: - //creating a frame –version-2.0.
import java.awt.*;
class MyFrame extends Frame
{
public static void main(String args[ ])
{
Ok listener
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{
public static void main(String args[ ])
{
//create an obj to Frame class
MyFrame f = new MyFrame();
//increase the size of frame
f.setSize(400,300);
//display the title
f.steTitle(“My AWT Frame”);
//display the frame
f.setVisible(true); (or) f.show();
//attach a WindowListener to the frame
f.addWindowListener(new WindowAdaptor()
{
public void windowClosing(windowEvent we)
{
System.exit(0);
}
});
}
}
class Myclass implements WindowAdaptor
{
public void windowClosing(windowEvent e){ }
{
System.exit(0);
}
}
addWindowListener(new windowAdaptor()
{
public void windowClosing(windowEvent e)
{
System.exit(0);
}
});
} //end of constructor
public void paint(Graphics g)
{
//set a background color for frame
setBackground(new color(100,20,20);
//set a text color
set.Color(Color.green);
//set a font for text
Font f = new Font(“Helvetica”, Font.BOLD+Font.ITALIC, 35);
g.setFont(f);
//now display the messages
g.drawString(“Hello Students”, 20, 100);
}
public static void main(String args[ ])
{
//create the frame
Message m = new Message();
//set the size of frame
m.setSize(500,400);
//set a title to the frame
m.steTitle(“My message”);
//display the frame
m.setVisible(true); (or) m.show();
}
}
To specify a color in awt: -
1. We can directly specify a color name from color class.
//vars
static Image img; //Θ Image is a class name & img is a variable.
//Default Constructor
Images()
{
//Load an image into img
img = Toolkit.getDefaultToolkit().getImage(“twist.gif”);
//To keep the processor with till image is loaded into image.
MediaTracker track = new MediaTracker(this); //Θ ’this’ is a current class object.
//now add image to track
track.addImage(img, 0); //Θ Here ‘0’ is Image ID No.
//wait till the image is loaded
try{
track.waitForID(0);
}catch(InterrputedException ie){ }
//close the frame
addWindowListener(new windowAdaptor()
{
public void windowClosing(windowEvent e)
{
System.exit(0);
}
});
} //close constructor
public void paint(Graphics g)
{
//Display the image in frame
g.drawImage(img, 50, 50, null);
}
public static void main(String[ ] args)
{
//create the frame
Image i = new Image();
//set the size of frame
i.setSize(500,400);
//set a title to the frame
i.steTitle(“My Image”);
//display the image in the title bar
i.setIconImage(img);
//display the frame
3. CheckBoxGroup ItemListener
4. Label ---
Note 1: - The above all Listener methods are all ‘public void’ methods.
Note 2: - A Listener can be added to a component using addxxxListener() method.
Ex: - addActionListener();
Note 3: - A Listener can be removed from a component using removexxxListener()
method.
Ex: - removeActionListener();
Note 4: - A Listener takes an object of xxxEvent class.
Ex: - actionPerformed(ActionEvent e);
if(str.equals(“Yellow”))
setBackground(Color.yellow);
if(str.equals(“Blue”))
setBackground(Color.blue);
if(str.equals(“Pink”))
setBackground(Color.pink);
}
public static void main(String args[ ])
{
//create the frame
MyButton mb = new MyButton();
//set the size of frame
mb.setSize(500,400);
//set a title to the frame
mb.steTitle(“My Push Buttons”);
//display the frame
mb.setVisible(true); (or) mb.show();
}
}
Frame: - Frame is also a component. A frame is a top level window that oes not
contain in another window. It is a container to place the components.
1. To create a Frame, extend your class to Frame class. Then create an object to our
class.
Creating Font: -
Font f = new Font();
setFont(f); //Component class methods also in Graphics class.
Creating Color: -
Ex 1: - setColor(Color.yellow);
Ex 2: - Color c = new Color(255, 0, 0);
//Θ (255, 0, 0) are R, G, B, Values respectively
setColor(c);
Maximum size of screen in pixels: -
1024 x 768, (or) 800 x 600 (or) 640 x 480
Check box: - A check box is a square shape box, which provides a set of options to
the user.
1. To create a check box:
Checkbox cb = new Checkbox(“label”);
2. To create a checked checkbox:
Checkbox cb = new Checkbox(“label”, null, true);
Here ‘null’ is checkbox group object.
3. To get the state of a checkbox
boolean b = cb.getState();
4. To get the state of Checkbox
cb.setState(true);
5. To get the label of a checkbox
String s = cb.getLabel();
6. To get the selected checkbox label into an array we can use getSelectedObjects();
method. This method returns an array size 1 only.
Object x[ ] = cb.getSelectedObjects();
Ex: - //CheckBoxes
import java.awt.*;
import java.awt.event.*;
class MyCheckbox extends Frame implements ItemListener
{
//Variables
Checkbox c1, c2, c3;
String msg = “ “;
MyCheckbox()
{
//Set flow layout manager
setLayout(new FlowLayout());
//Create 3 check boxes
c1 = new Checkbox(“Bold”, null, true);
c1 = new Checkbox(“Italic”);
c1 = new Checkbox(“Underline”);
//Add checkboxes to frame
add(c1);
add(c2);
add(c3);
//Add item listeners to checkboxes
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
//close the frame
addWindowListener(new windowAdaptor()
{
public void windowClosing(windowEvent we)
{
System.exit(0);
}
});
}
public void itemStateChanged(ItemEvent ie)
{
repaint(); // (or) call paint();
}
public void paint(Graphics g)
{
//Display the status of check boxes
g.drawString(“Status of Checkboxes”, 200, 100);
msg = “Bold: ”+e1.getState();
g.drawString(msg, 20, 120); //Θ 20, 120 are x, coordinates
msg = “Italic: ”+e2.getState();
g.drawString(msg, 20, 140);
msg = “Underline: ”+e3.getState();
g.drawString(msg, 20, 160);
}
public static void main(String args[ ])
{
//Create Frame
MyCheckbox mc = new MyCheckbox();
Choice menu (or) Choice Box: - Choice is a popup list of items. Only one item can
be selected.
1. To create a choice menu
Choice ch = new Choice();
2. To ad items to the choice menu
ch.add(“text”);
3. To know the name of the item selected from the choice menu
String s = ch.getSelectedItem();
4. To know the index of the currently selected item
int i = ch.getSelectedIndex();
This method returns -1 if nothing is selected.
Ex: - //Choice Box
import java.awt.*;
import java.awt.event.*;
class MyChoice extends Frame implements ItemListener
{
//Variables
String msg;
Choice ch;
MyChoice()
{
//Set flow layout manager
setLayout(new FlowLayout());
ch = new Choice();
//add items to choice box
ch.add(“Idly”);
ch.add(“Dosee”);
ch.add(“Chapathi”);
ch.add(“Veg Biryani”);
ch.add(“Parata”);
//Add the Choice box to the frame
add(ch);
//ad item listener to the choice box
ch.addItemListener(this);
//Window closing
addWindowListener(new windowAdaptor()
{
public void windowClosing(windowEvent we)
{
System.exit(0);
}
});
}
public void itemStateChanged(ItemEvent ie)
{
//call the paint()
repaint(); // (or) call paint();
}
public void paint(Graphics g)
{
ch.add(“Veg Biryani”);
ch.add(“Parata”);
//Add the Choice box to the frame
add(ch);
//ad item listener to the choice box
ch.addItemListener(this);
//Window closing
addWindowListener(new windowAdaptor()
{
public void windowClosing(windowEvent we)
{
System.exit(0);
}
});
}
public void itemStateChanged(ItemEvent ie)
{
//call the paint()
repaint(); // (or) call paint();
}
public void paint(Graphics g)
{
//know the user selected item
msg = ch.getSelectedItems();
g.drawString(“Selected items: ”, 10,150);
for(int i = 0; i<msg.length; i++)
{
g.drawString(msg[ i ], 10,170 + i * 20);
}
}
public static void main(String args[ ])
{
//Create Frame
MyChoice mc = new MyChoice();
MyText()
{
//Set flow layout manager
setLayout(new FlowLayout());
//create 2 labels
n = new Label(“Enter Name: ”, Label.RIGHT);
p = new Label(“Password: ”, Label.RIGHT);
//create 2 textfields
name = new TextField(20);
pass = new TextField(15);
//Hide the text filed in the pass filed
pass.setEchoChar(‘*’);
//add the components to the Frame
add(n);
add(name);
add(p);
add(pass);
//add actionListener to text fields
name.addActionListener(this);
pass.addActionListener(this);
//Closing for the Frame
addWindowListener(new windowAdaptor()
{
public void windowClosing(windowEvent we)
{
System.exit(0);
}
});
} //end of constructor
public void actionPerformed(ActionEvent ae)
{
//call the paint()
repaint(); // (or) call paint();
}
g.drawString(“Name: ”+name.getText(),20,100);
g.drawString(“Password: ”+pass.getText(),20,120);
}
public static void main(String[ ] args)
{
//Create Frame
MyText mt = new MyText();
//Set size and title
mt.setSize(500, 400);
mt.setTitle(“My Text Fields”);
//Display the frame
mt.setVisible(true); //(or) mr.show();
}
}
Ex: - //Moving from one frame to another frame
import java.awt.*;
import java.awt.event.*;
class Frame1 extends Frame implements ActionListener
{
//Variables
Button b;
//Constructor
Frame1()
{
//Closing for the Frame
addWindowListener(new windowAdaptor()
{
public void windowClosing(windowEvent we)
{
System.exit(0);
}
});
} //end of constructor
public void actionPerformed(ActionEvent ae)
{
//Go to the next frame
Frame2 f2 = new Frame2();
f2.setSize(300,300);
f2.setTitle(“My Next Window”);
f2.setVisible(true); //(or) f2.show();
}
public static void main(String args[ ])
{
//Create first Frame
Frame1 f1 = new Frame1();
//Set size and title
f1.setSize(500, 400);
f1.setTitle(“My Text Fields”);
//Display the frame
f1.setVisible(true); //(or) f1.show();
}
}
Save the above code as Frame1.java, compile it but not run the above code,
we have to write below code.
//This is Second Frame
import java.awt.*;
import java.awt.event.*;
class Frame2 extends Frame implements ActionListener
{
//Variables
Button b;
//Constructor
Frame2()
{
//Set flow layout manager
setLayout(new FlowLayout());
b = new Button(“Back”);
add(b);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
//Terminate the present frame
this.dispose();
}
}
Save the above code as Frame2.java, compile it but not run the above code,
initially we have to run the Frame1.java program. (or)
//Moving from one frame to another frame
import java.awt.*;
import java.awt.event.*;
class Frame1 extends Frame implements ActionListener
{
//Variables
Button b;
String str = “Hello”;
//Constructor
Frame1()
{
//Set flow layout manager
setLayout(new FlowLayout());
b = new Button(“Next”);
add(b);
b.addActionListener(this);
//Closing for the Frame
addWindowListener(new windowAdaptor()
{
public void windowClosing(windowEvent we)
{
System.exit(0);
}
});
} //end of constructor
public void actionPerformed(ActionEvent ae)
{
//Go to the next frame
Frame2 f2 = new Frame2(str);
f2.setSize(300,300);
f2.setTitle(“My Next Window”);
f2.setVisible(true); //(or) f2.show();
}
public static void main(String args[ ])
{
//Create first Frame
Frame1 f1 = new Frame1();
//Set size and title
f1.setSize(500, 400);
f1.setTitle(“My Text Fields”);
//Display the frame
f1.setVisible(true); //(or) f1.show();
}
}
Save the above code as Frame1.java, compile it but not run the above code,
we have to write below code.
//This is Second Frame
import java.awt.*;
import java.awt.event.*;
class Frame2 extends Frame implements ActionListener
{
//Variables
Button b;
String str;
//Constructor
Frame2(String str)
{
this.str = str;
AWT depends on native code. Native code internally creates the peer
component. Native code after creating the peer component it will returns the awt.
AWT depends on the Operating System.
All the AWT components are heavy weight components because they take
(or) use more resources of the system i.e. they take more memory and take more
time to process by the processor.
AWT
Peer Component based model
The look and feel of components is changing.
Heavy weight components
View Model
Presentation logic Controller Business logic
Model
Frame
Window Pane
Window Panes
Content Pane
our Components Title
Layered Pane
Components group
Root Pane
Background Components
Glass Pane
Foreground Components
JFrame
Container c = jf.getContentPane();
c.add(button); (Θ Here c is a Container Object).
Hierarchy of classes in Swing: -
Component JTabbedPane
JButton
Container JComponent JComboBox
JLabel JRadioButton
Window JWindow JToggleButton
JList JCheckbox
Frame JFrame JMenu
JmenuBar
JmenuItem JTextField
JTextComponent
JTextArea
|java.awt|-----------------------javax.swing------------------------|
Component, Container, Window, Frame these four classes are belongs to awt
package.
Creating a Frame: -
1. We can create a Frame b directly creating an object to JFrame
JFrame obj = new JFrame(“Title”);
2. Write a class that extends JFrame then create an object to it.
class MyClass extends JFrame
MyClass obj = new MyClass();
(Θ Here obj represents the JFrame)
Ex: - //Creating a Frame in Swing
import java.swing.*;
class MyFrame
{
public static void main(String args[ ])
{
//create the frame
JFrame obj = new JFrame(“My Swing Frame”);
//increase the size of the frame
obj.setSize(400,350);
1. Adding Components: -
To add a component to JFrame, we should add it to container as shown
below.
Container c = jf.getContentPane();
c.add(component);
(or) jf.get.getContentPane().add(component);
2. Removing Components: -
To remove a component
c.remove(component);
3. Setting colors for components: -
componet.setBackground(color);
componet.setForeground(color);
4. Setting line Borders: -
javax.swing.border.BorderFactory class is helpful to set different line borders.
Border bd = BorderFactory.createLineBorder(color.black,3);
Border bd = BorderFactory.createEtchedBorder();
Border bd = BorderFactory.createBevelBorder(BevelBorder.LOWERED);
Border bd = BorderFactory.createBevelBorder(BevelBorder.RAISED);
Border bd = BorderFactory.createMatteBorder(top,left,bottom,right,color.black);
component.setBorder(bd);
5. Setting tooltip to a component: -
component.setToolTipText(“This is a Swing Component”);
6. Setting a shotcut key: -
A shortcut key (mnemonic) is an underlined character used in labels, menus
and buttons. It is used with ALT key to select an option.
componet.setMnemonic(chart ‘c’);
7. Setting a Layout Manager: -
To set a LayoutManager for the Container
c.setLayout(LayoutManager obj);
Ex: - //A push button with all attributes
import java.awt.*;
import java.swing.*;
import java.swing.border.*;
class MyButtton extends JFrame
{
//variables
JButton b;
//default constructor
MyButtton()
{
//go to content pane
Container c = this.getContentPane();
//set a layout to contentpane
c.setLayout(new FlowLayout());
//Create ImageIcon object
ImageIcon ii = new ImageIcon(“twist.gif”);
//create push button with image on it
b = new JButton(“Click me”, ii);
//set colors to b
b.setBackground(Color.yellow);
b.setForeground(Color.red);
//set a font to b
Font f = new Font(“Arial”, Font.BOLD,25);
b.setFont(f);
//set bevel border around b
Border bd = BorderFactory.createBevelBorder(BevelBorder.RAISED);
b.setBorder(bd);
//set tooltip text for b
b.setToolTipText(“I am a lazy button”);
//set a shortcut key
b.setMnemonic(‘c’);
//add button to conten pane
c.add(b);
//close the frame
this.setDefaultOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[ ]);
{
//create the frame
MyButton mb = new MyButton();
//set size, title
mb.setTitle(“My Push Button”);
mb.setSize(500,400);
//display the frame
mb.setVisible(true);
}
}
Ex: - //A push button with all attributes
import java.awt.*;
import java.awt.event.*;
import java.swing.*;
import java.swing.border.*;
class MyButtton extends JFrame implement ActionListener
{
//variables
JButton b;
JLabel lbl;
//default constructor
MyButtton()
{
//go to content pane
Container c = this.getContentPane();
//set a layout to contentpane
c.setLayout(new FlowLayout());
//Create ImageIcon object
ImageIcon ii = new ImageIcon(“twist.gif”);
//create push button with image on it
b = new JButton(“Click me”, ii);
//set colors to b
b.setBackground(Color.yellow);
b.setForeground(Color.red);
//set a font to b
Font f = new Font(“Arial”, Font.BOLD,25);
b.setFont(f);
//set bevel border around b
Border bd = BorderFactory.createBevelBorder(BevelBorder.RAISED);
b.setBorder(bd);
//set tooltip text for b
b.setToolTipText(“I am a lazy button”);
//set a shortcut key
b.setMnemonic(‘c’);
//add button to conten pane
c.add(b);
//create an empty label and add to c
lbl = new Label();
lbl.setFont(“Impact”, Font.BOLD,25);
c.add(lbl):
//add ActionListener to the button
b.addActionListener(this);
//close the frame
this.setDefaultOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)
{
lbl.setText(“Hello Students”);
}
public static void main(String args[ ]);
{
//create the frame
MyButton mb = new MyButton();
//set size, title
mb.setTitle(“My Push Button”);
mb.setSize(500,400);
//display the frame
mb.setVisible(true);
}
}
To create a checkbox and radio buttons
JCheckBox cb = new JCheckBox(“label”, true);
JRadioButton rb = new JRadioButton(“label”, true);
}
public static void main(String[ ] args);
{
//create the frame
CheckRadio cr = new CheckRadio();
//set size, title
cr.setTitle(“My CheckBoxes and Radio Buttons”);
cr.setSize(500,400);
//display the frame
cr.setVisible(true);
}
}
Ex: - //Checkboxes and Radio buttons
import java.awt.*;
import java.awt.event.*;
import java.swing.*;
class CheckRadio extends JFrame implement ActionListener
{
//variables
JCheckBox cb1,cb2;
JRadioButton rb1,rb2;
JTextArea ta;
ButtonGroup bg;
String str = “ ”;
//default constructor
CheckRadio()
{
//reach the content pane
Container c = getContentPane(); (or) Container c = this.getContentPane();
//set a layout to contentpane
c.setLayout(new FlowLayout());
//create 2 check boxes
cb1 = new JCheckBox(“J2SE”, true);
cb2 = new JCheckBox(“J2EE”);
//set colors
cb1.setBackground(Color.yellow);
cb1.setForeground(Color.red);
cb1.setFont(new Font(“Sanserif”, Font_ITALIC,20);
//create 2 check boxes
rb1 = new JRadioButton(“Male”, true);
rb2 = new JRadioButton(“Female”);
//Specify these 2 RadioButtons belong to one group
bg = new ButtonGroup();
bg.add(rb1);
bg.add(rb2);
//create a text area
ta = new JTextArea(5,20);
//add all these components to c
c.add(cb1);
c.add(cb2);
c.add(rb1);
c.add(rb2);
c.add(ta);
//add ActionListener to the Checkboxes and Radio Buttons
cb1.addActionListener(this);
cb2.addActionListener(this);
rb1.addActionListener(this);
rb2.addActionListener(this);
//close the frame
this.setDefaultOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)
{
//To know the user selection
if(cb1.getModel().isSelected());
str +=”J2SE”;
if(cb2.getModel().isSelected());
str +=”J2EE”;
if(rb1.getModel().isSelected());
str +=”Male”;
if(rb2.getModel().isSelected());
str +=”Female”;
//send user selection to text area
ta.setText(str);
str=” ”;
}
public static void main(String[ ] args);
{
//create the frame
CheckRadio cr = new CheckRadio();
//set size, title
cr.setTitle(“My CheckBoxes and Radio Buttons”);
cr.setSize(500,400);
//display the frame
cr.setVisible(true);
}
}
A table represents several rows and columns of information.
JTable: - It represents data in the form of a table. The table can have rows of data,
and columns headings.
JTable Header
String arr[4][3]
data
By using String arr[ ] [ ] we can store only one type of data, if we want to store
different type of data it is better to use Vector.
1. To create a JTable
JTable tab = new JTable(data, column names);
Here data and column names can be a 2D 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);
row.add(object);
3. To create a Table heading, we use getTableHeader() method of JTable class.
JTableHeader head = tab.getTableHeader();
Note: - JTableHeader class is defined in javax.swing.table package.
Ex: - //Creating Employee Table
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
import java.util.*;
class Mytable extends JFrame
{
//Constructor
Mytable()
{
//take data of table as Vector object
Vector data = new Vector();
//Create first row
Vector row = new Vector();
//store column data in row
row.add(“Subba Rao”);
row.add(“System Analyst”);
row.add(“12,500.50”); (or) row.add(new Double(12,500.50));
//add this row to data table
data.add(row);
//Create Second row add to data
row = new Vector();
row.add(“Srinivasa Rao”);
row.add(“Sr. Programmer”);
row.add(“16,000.00”);
//add this row to data table
data.add(row);
//Create third row add to data
row = new Vector();
row.add(“Sudha Sree”);
row.add(“Receptionist”);
row.add(“35,000.75”);
//add this row to data table
data.add(row); North
add(c2);
add(c3);
}
}
JSplitPane: - JSplitPane is used to divide two (and only two) components.
1. Creating a JSplitPane
JSplitPane sp = new JSplitPane(orientation, component1, component2);
Here, orientation is JSplitPane.HORINZONTAL_SPLIT to align the componets
from left to right.
JSplitPane.VERTICAL_SPLIT to align the componets from top to bottom.
-----------
-----------
-----------
-----------
-----------
HORINZONTAL_SPLIT VERTICAL_SPLIT
{
//Variables
String str = “This is my text being displayed in the text area” + “And this
String will wrapped accorindly in the text area”;
JSplitPane sp;
JButton b;
JTextArea ta;
//Constructor
JSplitPaneDemo()
{
//Go to the content pane
Container c = getContenPane();
//set border layout to c
c.setLayout(new BorderLayout());
//create a push button
b = new JButton(“My Button”);
//create the text area
ta = new JTextArea();
//wrap the text in ta
ta.setLineWrap(true);
//create the split pane with b, ta
sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, ta);
//set the divider location
sp.setDividerLocation(300);
//add split pane to c
c.add(“Center”, sp);
//add action listener to b
b.addActionListener(this);
//Close the frame
setDefaultCloseOperaton(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)
{
//send str to ta
ta.setText(str);
}
public static void main(String args[ ])
{
//Create a frame
JSplitPaneDemo jsp = new JSplitPaneDemo();
jsp.setSize(500,400);
jsp.setTitle(“My Split Pane”);
jsp.setVisible(true);
}
}
JTree: - This component displays a set of hierachical data as an outline.
C:\ --------Root Noe (or) Root Directory
Java Progs ----------- Node DefaultMutableTreeNode
JButton.java ----------Leaf Node
JCheck.java
JRadioButton.java
1. Create a node of the tree (root node, or node, or leaf node) using
DefaultMutableTreeNode class.
DefaultMutableTreeNode node = new DefaultMutableTreeNode(“Java Programs”);
2. Add the tree by supplying root node
JTree tree = new JTree(root);
3. To find the path of selected of selected item
TreePath tp = tse.getNewLoadSelectionPath();
Θ Where tse – tree seletion event
4. To find the selected item in the tree
Object comp = tp.getLastPathComponent();
5. To know the path number (this represents the level)
int n = tp.getPathCount();
Ex: - //Creating a tree with directory names and file names
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*; //TreeSelectionListener
import javax.swing.tree.*; //TreePath
{
//Know the path of item selected
TreePath tp = tse.getNewLeadSelectionPath();
System.out.println(“Path of selected item = ” +tp);
//Know the item selected
Object comp = tp.getLastPathComponent();
System.out.println(“Item selected = ” +comp);
//Know the level of item selected
int n = tp.getPathCount();
System.out.println(“Level of item = ” +n);
}
public static void main(String args[ ])
{
//Create a frame
JTreeDemo demo = new JTreeDemo();
demo.setSize(500,400);
demo.setVisible(true);
}
} (or)
Ex: - //Creating a tree with directory names and file names
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*; //TreeSelectionListener
import javax.swing.tree.*; //TreePath
class JTreeDemo extends JFrame implements TreeSelectionListener
{
//Variables
JTree tree;
DefaultMutableTreeNode root;
//Constructor
JTreeDemo()
{
//Go to the content pane
Container c = getContenPane();
{
//Create a frame
JTreeDemo demo = new JTreeDemo();
demo.setSize(500,400);
demo.setVisible(true);
}
}
Menu: - A menu represents a group of options for the user to select.
Company Logo
Title bar
Creating a menu: -
Steps: -
1. Create menu bar using JMenuBar class
2. Add menu bar to the content pane.
3. Create menus using JMenu class.
4. Create menu items separately and add them to menus.
Creating a Sub menu: - Sub menu is a menu inside another menu.
Steps: -
1. Create a menu and add it to another menu.
2. Create menu items and add them to sub menu.
Creating a menu: -
1. Create a MenuBar
JMenuBar mb = new JMenuBar();
2. Attach this MenuBar to the container/Container Pane
c.add(mb);
3. Create separate menu to attach to the MenuBar
JMenu file = new JMenu(“File”);
Note: - Here, “File” is title for the menu which appears in the MenuBar.
4. Attach this menu to the MenuBar
mb.add(file);
5. Create menu items using JMenuItem or JCheckBoxMenuItem or
JRadioButtonMenuItem classes
JMenuItem nw = new JMenuItem(“New”);
6. Attach this menu item to the menu
file.add(new);
Creating a sub menu: -
7. Create a menu: -
JMenu font = new JMenu();
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 MenuItem or JCheckBoxMenuItem or JRadioButtonMenuItem.
Ex: - //Creating a menu
import java.awt.*; //It is for Container
import javax.swing.*; //It is for JMenu, MenuBar etc…
import javax.swing.event.*; //All Listeners in this package.
class MyMenu extends JFrame implements ActionListener
{
//Variables
JMenuBar mb;
JMenu file, edit, font;
JMenuItem op, cl, cp, pt;
JCheckBoxMenuItem pr;
//Constructor
MyMenu()
{
//Go to the content pane
Container c = getContenPane();
//set border layout to c
c.setLayout(new BorderLayout());
//create menu bar
mb = new JMenuBar();
//add menu bar to c
c.add(“North”, mb);
//Create file, edit menus
file = new JMenu(“File”);
edit = new JMenu(“File”);
//add file, edit menus to mb
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 op, cl to file menu
file.add(op);
file.add(cl);
//add cp, pt to edit menu
edit.add(cp);
edit.add(pt);
//disable close item
cl.setEnabled(false);
//Create Print check box as a menu item
pr = new JCheckBoxMenuItem(“Print”);
//add pr to file menu
file.add(pr);
//add a line
file.addSeparator();
//Create a font as a sub menu
font = new JMenu(“Font”);
op = new JMenuItem(“Open”);
cl = new JMenuItem(“Close”);
cp = new JMenuItem(“Copy”);
pt = new JMenuItem(“Paste”);
//add op, cl to file menu
file.add(op);
file.add(cl);
//add cp, pt to edit menu
edit.add(cp);
edit.add(pt);
//disable close item
cl.setEnabled(false);
//Create Print check box as a menu item
pr = new JCheckBoxMenuItem(“Print”);
//add pr to file menu
file.add(pr);
//add a line
file.addSeparator();
//Create a font as a sub menu
font = new JMenu(“Font”);
//add font to file menu
file.add(font);
//set a font for text
Font f = new Font(“Arail”);
Font f1 = new Font(“Times New Roman”);
//add menu items to font
font.add(f1);
font.add(f2);
//add listeners to menu items
op.addActionListener(this);
cl.addActionListener(this);
cp.addActionListener(this);
pt.addActionListener(this);
pr.addActionListener(this);
c.add(b1);
c.add(b2);
c.add(b3);
c.add(b4);
}
public static void main(String args[ ])
{
//Create a frame
GridLayoutDemo demo = new GridLayoutDemo();
demo.setSize(500,400);
demo.setVisible(true);
}
}
Ex: - //CardLayout Demo
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class CardLayoutDemo extends JFrame implements ActionListener
{
Container c;
CardLayout card;
//Constructor
CardLayoutDemo()
{
//Go to the content pane
c = getContenPane();
card = new CardLayout();
c.setLayout(card);
JButton b1, b2, b3;
b1 = new JButton(“Button1”);
b2 = new JButton(“Button2”);
b3 = new JButton(“Button3”);
c.add(“Fisrt Card”, b1);
c.add(“Second Card”,b2);
c.add(“Third Card”,b3);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
}
public void actionPerformed(ActionEvent ae);
{
card.next(c);
}
public static void main(String args[ ])
{
//Create a frame
CardLayoutDemo demo = new CardLayoutDemo();
demo.setSize(500,400);
demo.setVisible(true);
}
}
GridBagLayout: - It specifies the components
Button 1 Button 2 Button 3
in a grid like fashion, in which some
components span more than one row or
Button 4
column.
GridBagLayout()
1. It specify constraints for positioning of the
Button 5
components.
x=0 x=1 x=2
We can use GridBagConstraints
class object. y=0
GridBagConstriants()
gridx, gridy: - Specify the row and y=1 2, 1
column at the upper left of the
component. y=2
gridwidth, gridheight: - Specify the number of colums (for gridwidth) or rows (for
gridheight) in the components display area. The efault value is 1.
cons.fill = GridBagConstraints.HORIZONTAL;
cons.gridx = 0;
cons.gridy = 0;
cons.weightx = 0.7; //cons.weightx = 0.0;
gbag.setConstraints(b1, cons);
c.add(b1);
cons.gridx = 1;
cons.gridy = 0;
gbag.setConstraints(b2, cons);
c.add(b2);
cons.gridx = 1;
cons.gridy = 0;
gbag.setConstraints(b3, cons);
c.add(b3);
cons.gridx = 1;
cons.gridy = 0;
cons.ipady = 100; //make this component tall
cons.weightx = 0.0;
cons.gridwidth = 3;
gbag.setConstraints(b4, cons);
c.add(b4);
cons.gridx = 1; //aligned with button2
cons.gridy = 2; //third row
cons.ipady = 0; //reset to default
cons.weighty = 1.0; //request any extra vertical space
//button of space
cons.anchor = GridBagConstraints.PAGE_END;
//top padding
cons.insets = new Insets(10, 0, 0, 0);
//2 columns wide
cons.gridWidth = 2;
gbag.setConstraints(b5, cons);
c.add(b5);
}
Find Sum
13. Create a calculator using textfield and pushbuttons also ass the functionality to it.
14. Take a student class with H.No. Name and Marks in the Physcics, Maths and
Chemistry. Create the following screen which accepts H.No. and ddisplay the rest of
details in text fileld.
Retreive
Marks in Physcics:
Marks in Chemistry:
Marks in Maths:
Applet: - An applet is a program which comes from server travels on the internet
and executes in the client machine Applet is also java program.
Applet = Java Code + HTML Page
Server
Done Internet
Applet
Note: - public void paint(Graphics g) we can also use awt swing componets
JLabel n, a, I, lbl;
JTextField name;
JTextArea addr;
JList lst;
object x[ ];
JButton b1, b2;
Container c;
public void init()
{
//Create the frame and goto contentpane
JFrame jf = new JFrame();
c = jf.getContentPane();
c.setLayout(null);
c.setBackground(Color.yellow);
jf.setSize(500,400);
jf.setTitle(“My Form”);
jf.setVisible(true);
//Heading
lbl = new JLabel();
lbl.setText(“INetSolv Online Shopping Form”);
lbl.setFont(new Font(“Dailog”, Font.BOLD, 30););
lbl.setForeground(Color.red);
lbl.setBouns(200, 10, 500, 40);
c.add(lbl);
//name label and text field
n = new JLabel(“Enter Name”, JLabel.RIGHT);
name = new JTextField(20);
n.setBounds(50, 50, 100, 40);
name.setBounds(200, 50, 200, 40);
c.add(n);
c.add(name);
//add label an text area
a = new JLabel(“Enter Address”, JLabel.RIGHT);
addr = new JTextArea(6, 30);
Generic types are parameteize types: - This is introduced in Java 1.5. version.
Generic types represents classes or interfaces, which are type-safe. Generic
classes and interfaces Generic methods handle any type of data.
Generic types or declared as sub types of object class so they act upon any
class object. Generic types can’t act up on primitive types.
Ex: - //A generic class – to store any types of data
class MyClass
{
this.obj= obj;
}
integer.getObj()
{
return obj;
}
}
class Gent
{
public static void main(String args[ ])
{
Integer i = new Integer(100);
MyClass obj = new MyClass();
System.out.println(“U Stored” +obj.getObj());
Generic class: -
class MyClass
{
T obj;
MyClass()
{
this.obj = obj;
}
T.getObj()
{
return obj;
}
class Gen1
{
public static void main(String args[ ])
{
Integer i = new Integer(100);
MyClass< Integer> obj = new MyClass<Integer>();
System.out.println(“U Stored” +obj.getObj());
}
}
Ex: - //A generic method – to ispaly any type of array elements
class MyClass
{
static void display(int[ ] arr)
{
for(int i:arr) //this is for loop
System.out,println(i);
}
}
class Gen2
{
public static void main(String args[ ])
{
int arr1[ ] = {1, 2, 3, 4, 5};
MyClass.display(arr1);
}
}
2. class MyClass
{
static <GT>void display(GT[ ] arr)
{
for(GT i:arr) //this is for loop
System.out,println(i);
}
}
class Gen2
{
public static void main(String args[ ])
{
integer arr1[ ] = {1, 2, 3, 4, 5};
MyClass.display(arr1);
Double arr2[ ] = {1.1, 2.2, 3.3, 4.4, 5.5};
MyClass.display(arr2);
String arr3[ ] = {“Prasad”, “Siva”, “Srinu”, “Guru”};
MyClass.display(arr3);
}
}
Ex: - //Hashtable OS rewritten in JDK 1.5 as Hashtable <KV>
import java.util.*;
class HT
{
public static void main(String args[ ])
{
Hashtable ht = new Hashtable();
ht.put(“Ajay”, new Integer(50));
ht.put(“Sachin”, new Integer(100));;
String s =”Sachin”;
Integer score = (Integer) ht.get(s);
System.out.println(“Score = ” +score);
}
}
import java.util.*;
class HT
{
Hashtable<String, Integer> ht = new Hashtable<String, Integer>();
ht.put(“Ajay”, 50);
ht.put(“Sachin”, 100);;
String s =”Sachin”;
Integer score = (Integer) ht.get(s);
System.out.println(“Score = ” +score);
}
}
J2SE 1.5: -
To grasp the magnitude of the changes that J2SE 5 made to Java, consider
the following list of its major few features:
Genrics
Metadata
Autoboxing and auto-unboxing
Enumerations
Enchanced, for-each style for loop
Variable-length arguments (varagrs)
Static import
Formatted I/O
Concurrency utilities
Upgrades to the API
Generic class: -
1. A generic class or generic interface represents a class or an interface which is
type-safe.
2. A generic class, generic interface or a generic method can handle any type of
data.
3. Generic types are sub types of class object.
4. So they can act on objects of any class.
5. They cannot act on primitive data type.
6. Java compiler creates a non-generic versions using the specified data type from a
generic version.
7. When generic type is used, we can elimainate casting in any class.
8. The class of java.util have been rewritten using generic types.
9. We cannot create an object to generic type.
Ex: - class MyClass <T> //Invalid
T obj = new T(); //Invalid
H.W.
16. Write a generic metho swaps any two data types.
*****END*****