Unit 3 Java
Unit 3 Java
UNIT I
Overview and characteristics of Java, Java program Compilation and Execution Process Organization of the Java Virtual
Machine, JVM as an interpreter and emulator, Instruction Set, class File Format, Verification, Class Area, Java Stack, Heap,
Garbage Collection. Security Promises of the JVM, Security Architecture and Security Policy. Class loaders and security
aspects, sandbox model [T1,R2][No. of Hrs.: 11]
UNIT II
Java Fundamentals, Data Types & Literals Variables, Wrapper Classes, Arrays, Arithmetic Operators, Logical Operators,
Control of Flow, Classes and Instances, Class Member Modifiers Anonymous Inner Class Interfaces and Abstract Classes,
inheritance, throw and throws clauses, user defined Exceptions, The String Buffer Class, tokenizer, applets, Life cycle of
applet and Security concerns. [T1,T2][No. of Hrs.: 12]
UNIT III
Threads: Creating Threads, Thread Priority, Blocked States, Extending Thread Class, Runnable Interface, Starting Threads,
Thread Synchronization, Synchronize Threads, Sync Code Block, Overriding Synced Methods, Thread Communication,
wait, notify and notify all.AWT Components, Component Class, Container Class, Layout Manager Interface Default Layouts,
Insets and Dimensions, Border Layout, Flow Layout, Grid Layout, Card Layout Grid Bag Layout AWT Events, Event
Models, Listeners, Class Listener, Adapters, Action Event Methods Focus Event Key Event, Mouse Events, Window Event
[T2][No. of Hrs.: 11]
UNIT IV
Input/Output Stream, Stream Filters, Buffered Streams, Data input and Output Stream, Print Stream Random Access File,
JDBC (Database connectivity with MS-Access, Oracle, MS-SQL Server), Object serialization, Sockets, development of
client Server applications, design of multithreaded server. Remote Method invocation, Java Native interfaces, Development
of a JNI based application. Collection API Interfaces, Vector, stack, Hashtable classes, enumerations, set, List, Map,
Iterators. [T1][R1][No. of Hrs.: 10]
Thread:
A thread is actually a lightweight process. Unlike many other computer languages, Java
provides built-in support for multithreaded programming. A multithreaded program contains two
or more parts that can run concurrently. Each part of such a program is called thread and each
thread defines a separate path of execution. Thus, multithreading is a specialized form of
multitasking.
The Java Thread Model-Why use Threads in Java?
The Java run-time system depends on threads for many things. Threads reduce inefficiency by
preventing the waste of CPU cycles.
Multithreading in Java
Multithreading in Java is a process of executing multiple threads simultaneously.
However, we use multithreading than multiprocessing because threads use a shared memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize
the CPU. Multitasking can be achieved in two ways:
● Process-based Multitasking (Multiprocessing)
● Each process has an address in memory. In other words, each process allocates a separate
memory area.
● A process is heavyweight.
● Switching from one process to another requires some time for saving and loading registers,
memory maps, updating lists, etc.
● A thread is lightweight.
Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It
uses a shared memory area.
As shown in the above figure, a thread is executed inside the process. There is context-switching
between the threads. There can be multiple processes inside the OS, and one process can have
multiple threads.
Thread class:
Thread class provide constructors and methods to create and perform operations on a
● Thread()
● Thread(String name)
● Thread(Runnable r)
● Thread(Runnable r,String name)
to be executed by a thread. Runnable interface have only one method named run().
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs
following tasks:
Output:thread is running...
2) Java Thread Example by implementing Runnable interface
1. class Multi3 implements Runnable{
2. public void run(){
3. System.out.println("thread is running...");
4. }
5.
6. public static void main(String args[]){
7. Multi3 m1=new Multi3();
8. Thread t1 =new Thread(m1);
9. t1.start();
10. }
11. }
Output:thread is running...
If you are not extending the Thread class,your class object would not be treated as a
thread object.So you need to explicitly create Thread class object.We are passing the
object of your class that implements Runnable so that your class run() method may
execute.
System.out.println("Thread Running");
thread.start();
This example will print out the text "Thread running" once the run() method is executed by the new
thread.
Main Thread :
class MyTask{
void executeTask(){
for(int doc=1;doc<=10;doc++)
{
System.out.println("@@Printing documents #" +doc+ " -Printer2");
}
}
}
//Job-1
System.out.println("===Application Started===");
//job-2
MyTask task= new MyTask();
task.executeTask();
//Job-3
for(int doc=1;doc<=10;doc++)
{
System.out.println("^^Printing documents #" +doc+ " -Printer1");
}
//job-4
System.out.println("===Application Finished===");
}
}
Output:
===Application Started===
@@Printing documents #1 -Printer2
@@Printing documents #2 -Printer2
@@Printing documents #3 -Printer2
@@Printing documents #4 -Printer2
@@Printing documents #5 -Printer2
@@Printing documents #6 -Printer2
@@Printing documents #7 -Printer2
@@Printing documents #8 -Printer2
@@Printing documents #9 -Printer2
@@Printing documents #10 -Printer2
^^Printing documents #1 -Printer1
^^Printing documents #2 -Printer1
^^Printing documents #3 -Printer1
^^Printing documents #4 -Printer1
^^Printing documents #5 -Printer1
^^Printing documents #6 -Printer1
^^Printing documents #7 -Printer1
^^Printing documents #8 -Printer1
^^Printing documents #9 -Printer1
^^Printing documents #10 -Printer1
===Application Finished===
//Job-1
System.out.println("===Application Started===");
//job-2
MyTask task= new MyTask();
Thread t1=new Thread(task);
//task.executeTask();
task.start();
//Job-3
for(int doc=1;doc<=10;doc++)
{
System.out.println("^^Printing documents #" +doc+ " -Printer1");
}
//job-4
System.out.println("===Application Finished===");
}
}
Output-1;
===Application Started===
^^Printing documents #1 -Printer1
^^Printing documents #2 -Printer1
^^Printing documents #3 -Printer1
^^Printing documents #4 -Printer1
^^Printing documents #5 -Printer1
@@Printing documents #1 -Printer2
@@Printing documents #2 -Printer2
@@Printing documents #3 -Printer2
@@Printing documents #4 -Printer2
@@Printing documents #5 -Printer2
@@Printing documents #6 -Printer2
@@Printing documents #7 -Printer2
@@Printing documents #8 -Printer2
@@Printing documents #9 -Printer2
@@Printing documents #10 -Printer2
^^Printing documents #6 -Printer1
^^Printing documents #7 -Printer1
^^Printing documents #8 -Printer1
^^Printing documents #9 -Printer1
^^Printing documents #10 -Printer1
===Application Finished===
Output-2:
===Application Started===
^^Printing documents #1 -Printer1
^^Printing documents #2 -Printer1
^^Printing documents #3 -Printer1
^^Printing documents #4 -Printer1
^^Printing documents #5 -Printer1
^^Printing documents #6 -Printer1
^^Printing documents #7 -Printer1
^^Printing documents #8 -Printer1
^^Printing documents #9 -Printer1
^^Printing documents #10 -Printer1
===Application Finished===
@@Printing documents #1 -Printer2
@@Printing documents #2 -Printer2
@@Printing documents #3 -Printer2
@@Printing documents #4 -Printer2
@@Printing documents #5 -Printer2
@@Printing documents #6 -Printer2
@@Printing documents #7 -Printer2
@@Printing documents #8 -Printer2
@@Printing documents #9 -Printer2
@@Printing documents #10 -Printer2
Output-3:
===Application Started===
^^Printing documents #1 -Printer1
^^Printing documents #2 -Printer1
^^Printing documents #3 -Printer1
@@Printing documents #1 -Printer2
^^Printing documents #4 -Printer1
^^Printing documents #5 -Printer1
@@Printing documents #2 -Printer2
@@Printing documents #3 -Printer2
@@Printing documents #4 -Printer2
@@Printing documents #5 -Printer2
@@Printing documents #6 -Printer2
^^Printing documents #6 -Printer1
^^Printing documents #7 -Printer1
@@Printing documents #7 -Printer2
^^Printing documents #8 -Printer1
^^Printing documents #9 -Printer1
@@Printing documents #8 -Printer2
^^Printing documents #10 -Printer1
===Application Finished===
@@Printing documents #9 -Printer2
@@Printing documents #10 -Printer2
Through Runnable:
for(int doc=1;doc<=10;doc++)
{
System.out.println("@@Printing documents #" +doc+ " -Printer2");
}
}
}
public class HelloWorld{
//Job-1
System.out.println("===Application Started===");
//job-2
Runnable obj=new MyTask();
Thread t1=new Thread(obj);
//MyTask task= new MyTask();
//task.executeTask();
//task.start();
t1.start();
//Job-3
for(int doc=1;doc<=10;doc++)
{
System.out.println("^^Printing documents #" +doc+ " -Printer1");
}
//job-4
System.out.println("===Application Finished===");
}
}
Example 2:
package threads;
Output:
Hi
Hi
Hi
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hi
Hi
Hi
Hi
Hi
Hi
Hi
1. yield(): Suppose there are three threads t1, t2, and t3. Thread t1 gets the processor and
starts its execution and thread t2 and t3 are in Ready/Runnable state. Completion time
for thread t1 is 5 hour and completion time for t2 is 5 minutes. Since t1 will complete its
execution after 5 hours, t2 has to wait for 5 hours to just finish 5 minutes job. In such
scenarios where one thread is taking too much time to complete its execution, we need
a way to prevent execution of a thread in between if something important is pending.
yeild() helps us in doing so.
yield() basically means that the thread is not doing anything particularly important and
if any other threads or processes need to be run, they should run. Otherwise, the
current thread will continue to run.
● Once a thread has executed yield method and there are many threads with same
priority is waiting for processor, then we can't specify which thread will get
execution chance first.
● The thread which executes the yield method will enter in the Runnable state from
Running state.
● Once a thread pauses its execution, we can't specify when it will get chance again
it depends on thread scheduler.
● Underlying platform must provide support for preemptive scheduling if we are
using yield method.
2. sleep(): This method causes the currently executing thread to sleep for the specified
number of milliseconds, subject to the precision and accuracy of system timers and
schedulers.
Note:
yield() vs sleep()
he major difference between yield and sleep in Java is that yield() method pauses the
currently executing thread temporarily for giving a chance to the remaining waiting
threads of the same priority to execute. If there is no waiting thread or all the waiting
threads have a lower priority then the same thread will continue its execution.
yield:() indicates that the thread is not doing anything particularly important and if any other
threads or processes need to be run, they can. Otherwise, the c
urrent thread will continue to
run.
sleep(): causes the thread to definitely stop executing for a given amount of time; if no other
thread or process needs to be run, the CPU will be idle (and probably enter a power saving
mode).
3. join(): The join() method of a Thread instance is used to join the start of a thread’s
execution to end of other thread’s execution such that a thread does not start running
until another thread ends. If join() is called on a Thread instance, the currently running
thread will block until the Thread instance has finished executing.
The join() method waits at most this much milliseconds for this thread to die. A timeout
of 0 means to wait forever
Note:
● If any executing thread t1 calls join() on t2 i.e; t2.join() immediately t1 will enter
into waiting state until t2 completes its execution.
● Giving a timeout within join(), will make the join() effect to be nullified after the
specific timeout.
4. The stop() method of thread class terminates the thread execution. Once a thread is
stopped, it cannot be restarted by start() method.
Program:
}
}
}
System.out.println("exit from C");
}
}
}
}
Output:
start thread A
start thread B
From thread A: i= 1
From thread A: i= 2
From thread A: i= 3
From thread A: i= 4
From thread A: i= 5
exit from A
start thread C
From thread B: j= 1
From thread B: j= 2
From thread B: j= 3
end of main thread
From thread C: k= 1
From thread C: k= 2
From thread C: k= 3
From thread C: k= 4
From thread C: k= 5
exit from C
Thread Priorities:
}
System.out.println("exit from C");
}
}
}
}
Output:
start thread A
start thread B
start thread C
end of main thread
thread C started
From thread C: k= 1
From thread C: k= 2
From thread C: k= 3
From thread C: k= 4
From thread C: k= 5
exit from C
thread B started
From thread B: j= 1
From thread B: j= 2
From thread B: j= 3
From thread B: j= 4
From thread B: j= 5
exit from B
thread A started
From thread A: i= 1
From thread A: i= 2
From thread A: i= 3
From thread A: i= 4
From thread A: i= 5
exit from A
Synchronization in Java
Synchronization in java is the capability to control the access of multiple threads to any shared
resource.
Java Synchronization is better option where we want to allow only one thread to access the shared
resource.
When a thread invokes a synchronized method, it automatically acquires the lock for that object
and releases it when the thread completes its task.
package threads;
class One
{
int count=0;
for(int i=1;i<10;i++)
count++;
One o;
Two(One o)
this.o=o;
o.increment();
}
public class SynDemo
tw1.start();
tw2.start();
Output:
count is =1
count is =1
count is =2
count is =3
count is =2
count is =4
count is =3
count is =5
count is =4
count is =6
count is =7
count is =8
count is =9
count is =5
count is =6
count is =7
count is =8
count is =9
With Synchronization;
package threads;
class AA
int count=0;
for(int i=1;i<10;i++)
{
count++;
AA o;
BB(AA o)
this.o=o;
o.increment();
{
public static void main(String[] args)
tw1.start();
tw2.start();
Output:
count is =1
count is =2
count is =3
count is =4
count is =5
count is =6
count is =7
count is =8
count is =9
count is =1
count is =2
count is =3
count is =4
count is =5
count is =6
count is =7
count is =8
count is =9
Synchronized block:
import java.io.*;
import java.util.*;
class Sender
{
System.out.println("Sending\t" + msg );
try
Thread.sleep(1000);
catch (Exception e)
System.out.println("Thread interrupted.");
Sender sender;
{
msg = m;
sender = obj;
synchronized(sender)
sender.send(msg);
// Driver class
S1.start();
S2.start();
try
S1.join();
S2.join();
catch(Exception e)
System.out.println("Interrupted");
Output:
Sending Hi
Hi Sent
Sending Bye
Bye Sent
1. class Table{
2. void printTable(int n){//method not synchronized
3. for(int i=1;i<=5;i++){
4. System.out.println(n*i);
5. try{
6. Thread.sleep(400);
7. }catch(Exception e){System.out.println(e);}
8. }
9. }
10. }
11.
12. class MyThread1 extends Thread{
13. Table t;
14. MyThread1(Table t){
15. this.t=t;
16. }
17. public void run(){
18. t.printTable(5);
19. }
20.
21. }
22. class MyThread2 extends Thread{
23. Table t;
24. MyThread2(Table t){
25. this.t=t;
26. }
27. public void run(){
28. t.printTable(100);
29. }
30. }
31.
32. class TestSynchronization1{
33. public static void main(String args[]){
34. Table obj = new Table();//only one object
35. MyThread1 t1=new MyThread1(obj);
36. MyThread2 t2=new MyThread2(obj);
37. t1.start();
38. t2.start();
39. }
40. }
Output: 5
100
10
200
15
300
20
400
25
500
Output: 5
10
15
20
25
100
200
300
400
500
Syntax
1. public final boolean isAlive()
Return
This method will return true if the thread is alive otherwise returns false.
Example
1. public class JavaIsAliveExp extends Thread
2. {
3. public void run()
4. {
5. try
6. {
7. Thread.sleep(300);
8. System.out.println("is run() method isAlive "+Thread.currentThread().isAlive());
9. }
10. catch (InterruptedException ie) {
11. }
12. }
13. public static void main(String[] args)
14. {
15. JavaIsAliveExp t1 = new JavaIsAliveExp();
16. System.out.println("before starting thread isAlive: "+t1.isAlive()); //false
17. t1.start();
18. System.out.println("after starting thread isAlive: "+t1.isAlive()); //true
19. }
20. }
Output:
1) wait() method
Causes current thread to release the lock and wait until either another thread invokes
the notify() method or the notifyAll() method for this object, or a specified amount of time has
elapsed. (Running -> Suspended state)
The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.
Method Description
public final void wait(long timeout)throws waits for the specified amount of
InterruptedException time.
2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting
on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the
discretion of the implementation. Syntax:
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
Why wait(), notify() and notifyAll() methods are defined in Object class
not Thread class?
It is because they are related to lock and object has a lock.
wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.
should be notified by notify() or notifyAll() after the specified amount of time, sleep is
methods completed.
Example of inter thread communication in java
Let's see the simple example of inter thread communication.
1. class Customer{
2. int amount=10000;
3. synchronized void withdraw(int amount){
4. System.out.println("going to withdraw...");
5.
6. if(this.amount<amount){ //10000<15000
7. System.out.println("Less balance; waiting for deposit..." );
8. try{wait();}catch(Exception e){}
9. }
10. this.amount-=amount; //20000-15000
11. System.out.println("...amount= " + this.amount);//5000
12. System.out.println("withdraw completed...");
13. }
14. synchronized void deposit(int amount){
15. System.out.println("going to deposit...");
16. this.amount+=amount; //10000+10000
17. System.out.println("deposit completed...amount= " + this.amount); //20000
18. notify();
19. }
20. }
21. public class Test{
22. public static void main(String args[]){
23. final Customer c=new Customer();
24. new Thread()
25. {
26. public void run(){c.withdraw(15000);}
27. }.start();
28. new Thread(){
29. public void run(){c.deposit(10000);}
30. }.start();
31. }}
32.
33.
The java.awt package provides classes for AWT api such as TextField, Label,
TextArea, RadioButton, CheckBox, Choice, List etc.
public void setSize(int width,int height) sets the size (width and height) of the component.
public void setLayout(LayoutManager defines the layout manager for the component.
m)
public void setVisible(boolean status) changes the visibility of the component, by default
false.
1. import java.awt.*;
2. class First extends Frame{
3. First(){
4. Button b=new Button("click me");
5. b.setBounds(30,100,80,30);// setting button position
6. add(b);//adding button into frame
7. setSize(300,300);//frame size 300 width and 300 height
8. setLayout(null);//no layout manager
9. setVisible(true);//now frame will be visible, by default not visible
10. }
11. public static void main(String args[]){
12. First f=new First();
13. }}
The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above example that
sets the position of the awt button.
AWT Example by Association
Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are
showing Button component on the Frame.
1. import java.awt.*;
2. class First2{
3. First2(){
4. Frame f=new Frame();
5. Button b=new Button("click me");
6. b.setBounds(30,50,80,30);
7. f.add(b);
8. f.setSize(300,300);
9. f.setLayout(null);
10. f.setVisible(true);
11. }
12. public static void main(String args[]){
13. First2 f=new First2();
14. }}
Container
Container is a component in AWT that contains another component like button, text field,
tables etc. Container is a subclass of component class. Container class keeps track of
components that are added to another component.
Panel
Panel class is a concrete subclass of Container. Panel does not contain title bar, menu bar or
border. It is container that is used for holding components.
Window class
Window class creates a top level window. Window does not have borders and menubar.
Frame
Frame is a subclass of Window and have resizing canvas. It is a container that contain several
different components like button, title bar, textfield, label etc. In Java, most of the AWT
applications are created using Frame window. Frame class has two different constructors,
Creating a Frame
There are two ways to create a Frame. They are,
1. By Instantiating Frame class
import java.awt.*;
import java.awt.event.*;
}
Points to Remember:
1. While creating a frame (either by instantiating or extending Frame class), Following two
○ setVisible(true);
2. When you create other components like Buttons, TextFields, etc. Then you need to add
3. You can add the following method also for resizing the frame - setResizable(true);
AWT Button
In Java, AWT contains a Button Class. It is used for creating a labelled button which can
perform an action.
Example:
Lets take an example to create a button and it to the frame by providing coordinates.
import java.awt.*;
public class ButtonDemo1
{
public static void main(String[] args)
{
Frame f1=new Frame("==> Button Demo");
Button b1=new Button("Press Here");
b1.setBounds(80,200,80,50);
f1.add(b1);
f1.setSize(500,500);
f1.setLayout(null);
f1.setVisible(true);
}
}
AWT Label
In Java, AWT contains a Label Class. It is used for placing text in a container. Only Single line
text is allowed and the text can not be changed directly.
Label Declaration:
public class Label extends Component implements Accessible
Example:
In this example, we are creating two labels to display text to the frame.
import java.awt.*;
class LabelDemo1
{
public static void main(String args[])
{
Frame l_Frame= new Frame("studytonight ==> Label Demo");
Label lab1,lab2;
lab1=new Label("Welcome to studytonight.com");
lab1.setBounds(50,50,200,30);
lab2=new Label("This Tutorial is of Java");
lab2.setBounds(50,100,200,30);
l_Frame.add(lab1);
l_Frame.add(lab2);
l_Frame.setSize(500,500);
l_Frame.setLayout(null);
l_Frame.setVisible(true);
}
}
AWT TextField
In Java, AWT contains aTextField Class. It is used for displaying single line text.
TextField Declaration:
public class TextField extends TextComponent
Example:
We are creating two textfields to display single line text string. This text is editable in nature,
see the below example.
import java.awt.*;
class TextFieldDemo1{
public static void main(String args[]){
Frame TextF_f= new Frame("studytonight ==>TextField");
TextField text1,text2;
text1=new TextField("Welcome to studytonight");
text1.setBounds(60,100, 230,40);
text2=new TextField("This tutorial is of Java");
text2.setBounds(60,150, 230,40);
TextF_f.add(text1);
TextF_f.add(text2);
TextF_f.setSize(500,500);
TextF_f.setLayout(null);
TextF_f.setVisible(true);
}
}
AWT TextArea
In Java, AWT contains aTextArea Class. It is used for displaying multiple-line text.
TextArea Declaration:
public class TextArea extends TextComponent
Example:
In this example, we are creating a TextArea that is used to display multiple-line text string and
allows text editing as well.
import java.awt.*;
public class TextAreaDemo1
{
TextAreaDemo1()
{
Frame textArea_f= new Frame();
TextArea area=new TextArea("Welcome to studytonight.com");
area.setBounds(30,40, 200,200);
textArea_f.add(area);
textArea_f.setSize(300,300);
textArea_f.setLayout(null);
textArea_f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaDemo1();
}
}
AWT Checkbox
In Java, AWT contains a Checkbox Class. It is used when we want to select only one option i.e
true or false. When the checkbox is checked then its state is "on" (true) else it is "off"(false).
Checkbox Syntax
public class Checkbox extends Component implements ItemSelectable, Accessible
Example:
In this example, we are creating checkbox that are used to get user input. If checkbox is
checked it returns true else returns false.
import java.awt.*;
public class CheckboxDemo1
{
CheckboxDemo1(){
Frame checkB_f= new Frame("studytonight ==>Checkbox Example");
Checkbox ckbox1 = new Checkbox("Yes", true);
ckbox1.setBounds(100,100, 60,60);
Checkbox ckbox2 = new Checkbox("No");
ckbox2.setBounds(100,150, 60,60);
checkB_f.add(ckbox1);
checkB_f.add(ckbox2);
checkB_f.setSize(400,400);
checkB_f.setLayout(null);
checkB_f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxDemo1();
}
}
AWT CheckboxGroup
In Java, AWT contains aCheckboxGroup Class. It is used to group a set of Checkbox. When
Checkboxes are grouped then only one box can be checked at a time.
CheckboxGroup Declaration:
public class CheckboxGroup extends Object implements Serializable
Example:
This example creates a checkboxgroup that is used to group multiple checkbox in a single unit.
It is helpful when we have to select single choice among the multiples.
import java.awt.*;
public class CheckboxGroupDemo
{
CheckboxGroupDemo(){
Frame ck_groupf= new Frame("studytonight ==>CheckboxGroup");
CheckboxGroupobj = new CheckboxGroup();
Checkbox ckBox1 = new Checkbox("Yes", obj, true);
ckBox1.setBounds(100,100, 50,50);
Checkbox ckBox2 = new Checkbox("No", obj, false);
ckBox2.setBounds(100,150, 50,50);
ck_groupf.add(ckBox1);
ck_groupf.add(ckBox2);
ck_groupf.setSize(400,400);
ck_groupf.setLayout(null);
ck_groupf.setVisible(true);
}
public static void main(String args[])
{
new CheckboxGroupDemo();
}
}
AWT Choice
In Java, AWT contains a Choice Class. It is used for creating a drop-down menu of choices.
When a user selects a particular item from the drop-down then it is shown on the top of the
menu.
Choice Declaration:
public class Choice extends Component implements ItemSelectable, Accessible
Example:
In this example, we are creating drop-down menu that is used to get user choice from multiple
choices.
import java.awt.*;
public class ChoiceDemo
{
ChoiceDemo()
{
Frame choice_f= new Frame();
Choice obj=new Choice();
obj.setBounds(80,80, 100,100);
obj.add("Red");
obj.add("Blue");
obj.add("Black");
obj.add("Pink");
obj.add("White");
obj.add("Green");
choice_f.add(obj);
choice_f.setSize(400,400);
choice_f.setLayout(null);
choice_f.setVisible(true);
}
public static void main(String args[])
{
new ChoiceDemo();
}
}
AWT List
In Java, AWT contains a List Class. It is used to represent a list of items together. One or more
than one item can be selected from the list.
List Declaration:
public class List extends Component implements ItemSelectable, Accessible
Example:
In this example, we are creating a list that is used to list out the items.
import java.awt.*;
public class ListDemo
{
ListDemo()
{
Frame list_f= new Frame();
List obj=new List(6);
obj.setBounds(80,80, 100,100);
obj.add("Red");
obj.add("Blue");
obj.add("Black");
obj.add("Pink");
obj.add("White");
obj.add("Green");
list_f.add(obj);
list_f.setSize(400,400);
list_f.setLayout(null);
list_f.setVisible(true);
}
public static void main(String args[])
{
new ListDemo();
}
}
AWT Canvas
In Java, AWT contains a Canvas Class. A blank rectangular area is provided. It is used when a
user wants to draw on the screen.
Declaration:
public class Canvas extends Component implements Accessible
Example:
The canvas is used to provide a place to draw using mouse pointer. We can used it to get user
architectural user input.
import java.awt.*;
public class CanvasDemo1
{
public CanvasDemo1()
{
Frame canvas_f= new Frame("studytonight ==> Canvas");
canvas_f.add(new CanvasDemo());
canvas_f.setLayout(null);
canvas_f.setSize(500, 500);
canvas_f.setVisible(true);
}
public static void main(String args[])
{
new CanvasDemo1();
}
}
class CanvasDemo extends Canvas
{
public CanvasDemo() {
setBackground (Color.WHITE);
setSize(300, 200);
}
public void paint(Graphics g)
{
g.setColor(Color.green);
g.fillOval(80, 80, 150, 75);
}
}
Java AWT Panel
The Panel is a simplest container class. It provides space in which an application can attach any
other component. It inherits the Container class.
Output:
The object of Menu class is a pull down menu component which is displayed on the menu bar. It
inherits the MenuItem class.
Frame vs Dialog
Frame and Dialog both inherits Window class. Frame has maximize and minimize buttons but
Dialog doesn't have.
Output:
Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an
interface that is implemented by all the classes of layout managers. There are following classes
that represents the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
Example: Here is the image of a Frame where eight buttons have been added to a
Frame under Flow layout. As you can see buttons 7 & 8 are in second row because first
six buttons consumed all horizontal space.
Points to Note:
● All rows in Flow layout are center aligned by default. As you can see in
the above image that buttons 7 & 8 are in center. However we can set the
alignment to left or right, we will learn about it later in this post.
● The default horizontal and vertical gap between components is 5 pixels.
● By default the components Orientation is left to right, which means the
components would be added from left to right, however we can change it to
right to left as well, we will see that later in this post.
import java.awt.*;
public class FlowLayoutDemo extends Frame{
// constructor
public FlowLayoutDemo(String title)
{
/* It would create the Frame by calling Frame(String title)
* the constructor of Frame class.
*/
super(title);
import java.awt.*;
public class FlowLayoutDemo extends Frame{
// constructor
public FlowLayoutDemo(String title)
{
/* It would create the Frame by calling
* the constructor of Frame class.
*/
super(title);
Output:
The diagram above is the output of below code, where I have added five buttons (which
have same name as regions in which they have been placed) to the five regions of
Border Layout. You can add any component of your choice in a similar manner.
import java.awt.*;
public class BorderDemo extends Frame{
// constructor
public BorderDemo(String title)
{
/* It would create the Frame by calling the constructor of Frame
class.*/
super(title);
//Setting up Border Layout
setLayout(new BorderLayout());
//Creating a button and adding it to PAGE_START area
Button b1 = new Button("PAGE_START");
add(b1, BorderLayout.PAGE_START);
1) Notice the statement setLayout(new BorderLayout( )); in the example above, if you
change it to this: setLayout(new BorderLayout(50,20)); then the output Frame would
look like the image below. Here 50 is horizontal gap and 20 is vertical gap.
Method details:
Constructs a border layout with the specified gaps between components. The
horizontal gap is specified by hgap and the vertical gap is specified by vgap.
Parameters:
2) You can also do it by using setHgap(int hgap) method for horizontal gap between
components and setVgap(int vgap) method for vertical gap.
Java GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is
1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the
given rows and columns alongwith given horizontal and vertical gaps.
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);
f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyGridLayout();
}
}
Event Handling in AWT JAVA
What is an Event?
Change in the state of an object is known as event i.e. event describes the change in state
of source. Events are generated as result of user interaction with the graphical user interface
components. For example, clicking on a button, moving the mouse, entering a character
through a keyboard, selecting an item from a list, scrolling the page are the activities that
cause an event to happen.
Types of Event
The events can be broadly classified into two categories:
● Foreground Events - Those events which require the direct interaction of the user.
They are generated as consequences of a person interacting with the graphical
components in Graphical User Interface. For example, clicking on a button, moving the
mouse, entering a character through the keyboard,selecting an item from a list, scrolling
the page etc.
● Background Events - Those events that require the interaction of the end user are
known as background events. Operating system interrupts, hardware or software
failure, timer expires, and operation completion are the example of background events.
Callback Methods
These are the methods that are provided by API provider and are defined by the application
programmer and invoked by the application developer. Here the callback methods represents
an event method. In response to an event java jre will fire callback method. All such callback
methods are provided in listener interfaces.
If a component wants some listener will listen to it's events the the source must register itself
to the listener.
Event and Listener (Java Event Handling)
Changing the state of an object is known as an event. For example, click on button, dragging
mouse etc. The java.awt.event package provides many event classes and Listener interfaces for
event handling.
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
Components of Event Handling
Event handling has three main components,
● Listeners : A listener is an object that listens to the event. A listener gets notified when
an event occurs
Registration Methods
For registering the component with the Listener, many classes provide the registration methods.
For example:
● Button
● MenuItem
● TextField
● Checkbox
● Choice
● List
1. Within class
2. Other class
3. Anonymous class
package AWTDemo;
import java.awt.*;
import java.awt.event.*;
class ActionDemo extends Frame implements ActionListener{
TextField tf;
ActionDemo(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passing current instance
Example-2:
package AWTDemo;
import java.awt.*;
import java.awt.event.*;
Output:
Java MouseListener Interface
The Java MouseListener is notified whenever you change the state of mouse. It is notified against
MouseEvent. The MouseListener interface is found in java.awt.event package. It has five methods.
Output:
Method Description
public void windowClosing(WindowEvent This method is called a user clicks on the (x) icon
ke) to close the window.
public void windowClosed(WindowEvent e) This method is called when a window has been
closed.
● AW
indowEvent event source is a window in which such event is generated, must call its
method -
Method Description
import java.awt.event.*;
Label label1;
Frame frame;
WindowEx1()
{
frame.add(label1);
//Registering class WindowEx1 to catch and respond to window events
frame.addWindowListener(this);
frame.setSize(340,200);
frame.setVisible(true);
}
public void windowActivated(WindowEvent we)
{
System.out.println("Window Activated");
}
System.out.println("Window Closed");
}
public void windowClosing(WindowEvent we)
{
frame.dispose();
System.out.println("Window Closing");
}
public void windowDeactivated(WindowEvent we)
{
System.out.println("Window Deactivated");
}
public void windowDeiconified(WindowEvent we)
System.out.println("Window Deiconified");
}
System.out.println("Window Iconified/minimized");
}
new WindowEx1();
}
}
When you run the code, you are presented a window shown in the window below -:
Figure 1
At the command prompt you are displayed two messages, due to the execution of methods in
sequence:
● windowActivated()
● windowOpened()
Window Activated
When you click on the minimize button of this window to minimize it, the window is deactivated
and deiconified.
Figure 2
Hence, two new messages are displayed on the command prompt, due to the execution of
methods in sequence:
● windowDeiconified()
● windowDeactivated()
Window Iconified/minimized
Window Deactivated
Figure 3
Hence, a new message is displayed on the command prompt, due to the execution of the method:
● windowActivated()
Window Activated
When you click on the (x) button of this window to close it, the window is deactivated and closed.
Figure 4
Hence, three new messages are displayed on the command prompt, due to the execution of
methods in sequence:
● windowClosing()
● windowDeactivated()
● windowClosed()
Window Closing
Window Deactivated
Window Closed
Output:
AWT FocusListener Interface
Introduction
The interfaceFocusListener is used for receiving keyboard focus events. The class that
process focus events needs to implements this interface.
Class declaration
Following is the declaration for java.awt.event.FocusListener interface:
public interface FocusListener
extends EventListener
Interface methods
S.N. Method & Description
1 void focusGained(FocusEvent e)
2
void focusLost(FocusEvent e)
Methods inherited
This class inherits methods from the following interfaces:
● java.awt.event.EventListener
package AWTDemo;
import java.awt.*;
import java.awt.event.*;
public FocusListenertest()
{
add(b1=new Button ("First"),"South");
add(b2=new Button ("Second"),"North");
b1.addFocusListener(this);// registering
b2.addFocusListener(this);
setSize(200,200);
}
public void focusGained(FocusEvent fe) //method of focuslistener
{
if(fe.getSource()==b1)
System.out.println(b1.getLabel()+"gained");
if(fe.getSource()==b2)
System.out.println(b2.getLabel()+"gained");
if(fe.isTemporary())
System.out.println("Temporary Focus");
}
public void focusLost(FocusEvent fe) //in focusevent "getID()"is a
method
{
if(fe.getSource()==b1)
System.out.println(b1.getLabel()+"lost");
if(fe.getSource()==b2)
System.out.println(b2.getLabel()+"lost");
}
public static void main(String a[])
{
new FocusListenertest().setVisible(true);
}
}
Output:
Firstgained
Firstlost
Secondgained
Secondlost
Method Description
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
java.awt.dnd Adapter classes
Adapter class Listener interface
DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener
MouseInputAdapter MouseInputListener
InternalFrameAdapter InternalFrameListener
Adapters are abstract classes for receiving various events. The methods in these classes are
empty. These classes exists as convenience for creating listener objects.
AWT Adapters:
Following is the list of commonly used adapters while listening GUI events in AWT.
5
WindowAdapter: An
Ex-1 MouseAdapter
package AWTDemo;
import java.awt.*;
import java.awt.event.*;
public class MouseAdapterExample extends MouseAdapter{
Frame f;
MouseAdapterExample(){
f=new Frame("Mouse Adapter");
f.addMouseListener(this);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void mouseClicked(MouseEvent e) {
Graphics g=f.getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
}
public static void main(String[] args) {
new MouseAdapterExample();
}
}