Java Unit4
Java Unit4
Topics to be Covered:
1.Multi-Threaded Programming
2.Interrupting Thread
3.Thread States
4.Thread Properties
5.Thread Synchronization
6.Thread-Safe Collections
7.Executors
8.Synchronizers
9.Threads and Event-Driven Programming
INTRODUCTION
1. Multithreading extends the idea of multitasking into applications, so you can
subdivide specific operations within a single application into individual
threads. Each of the threads can run in parallel.
2. Those who are familiar with the modern operation systems such as windows 95
may recognize that they can execute several programs simultaneously. This
ability is known as multitasking. In Systems terminology, it is called
multithreading.
3. Multithreading is a conceptual programming paradigm where a program is
divided into two or more subprograms, which can be implemented at the
same time in parallel.
4. In most of our computers, we have only a single processor and therefore, in
reality, the processor is doing only one thing at a time. However, the
processor switches between the processes so fast that it appears to human
beings that all of them are being done simultaneously.
5. Java programs contain only a single sequential flow of control. This is what
happens when we execute a normal program. The program begins, runs
through a sequence of executions, and finally ends. At any given point of
time, there is only one statement under execution.
6. A thread is similar to a program that has a single flow of control. It has a
beginning, a body and an end, and executes commands sequentially. In fact, all
main programs in our earlier examples can be called single threaded
programs.
class ABC
{
--------------------------------------------------------------------------------------------------------------}
Beginning
Single
threaded body
of execution
End
MULTITHREADED PROGRAM
Main Thread
_______________
_______________
_______________
_______________
_______________
_______________
_______________
_______________
star
t
_______________
_______________
_______________
_______________
_______________
_______________
_______________
_______________
Thread A
switchin
g
star
t
_______________
_______________
_______________
_______________
_______________
_______________
_______________
_______________
Thread B
Main method
module
star
t
switchin
g
_______________
_______________
_______________
_______________
_______________
_______________
_______________
_______________
Thread C
CREATING THREADS
1. Creating threads in Java is simple.
2. Threads are implemented in the form of objects that contain a
method
called run().
3. The run() method is the heart and soul of any thread. It makes
up the
entire body of a thread and is the only method in which the
threads
behavior can be implemented.
4. A typical
run()
would
appear as follows:
public
void
run()
{
----------------------------------Statements for implementing
-----------------thread
}
initiate the
1. Declaring the
class
class MyThread extends Thread
{
--------------------------------------------------------}
3. Starting New
Thread
MyThread aThread = new MyThread();
aThread.start();
Output:
From Thread A : i = 1
From Thread C : k =
From Thread B : j =
From Thread C : k =
From Thread A : i =
From Thread C : k =
From Thread B : j =
From Thread C : k =
From Thread A : i =
From Thread C : k =
From Thread B : j =
Exit from C
From Thread A : i =
From Thread B : j =
From Thread A : i =
From Thread B : j =
Exit from A
Exit from B
import java.lang.Thread;
class X implements Runnable
{
public void run()
{
for(int i = 1;i <= 5;i++)
{
System.out.println("\tFrom Thread A : i = " + i);
}
System.out.println("Exit from A ");
}
}
class Y implements Runnable
{
public void run()
{
for(int j = 1;j <= 5;j++)
{
System.out.println("\tFrom Thread B : j = " + j);
}
System.out.println("Exit from B ");
}
}
Interrupting Thread:
Using sleep() method:
Make the thread to sleep for a while. In that particular sleep time the
processor executes the other Threads which is ready for an execution.
It should thrown a exception called java.lang.InterruptedException, so it
must be handled in the program using try-catch.
Syntax:
Thread.sleep(millisec);
class A implements Runnable
{
public void run()
{
try{
for(int i = 1;i <= 5;i++)
{
System.out.println("\tFrom Thread A : i = " +
i);
Thread.sleep(1000);
}
}
catch(InterruptedException e) {
System.out.println("Thread 1 Interrupted");
}
System.out.println("Exit from A ");
Meaning
getName()
getPriority()
isAlive()
join()
run()
sleep()
start()
currentThread(
)
LIFE CYCLE OF A
THREAD
During the life time of a thread, there are many states it can enter.
They include
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
Newborn
start
stop
Active Thread
Runnable
Running
stop
Dead
yield
suspen
d
resum
e
sleep
notify
wait
Idle Thread
(Not
Runnable)
Killed
Thread
Blocked
stop
import java.lang.Thread;
class A extends Thread
{
public void run()
{
for(int i = 1;i <= 5;i++)
{
if(i == 1) yield();
System.out.println("\tFrom Thread A : i = " + i);
}
System.out.println("Exit from A ");
}
}
class B extends Thread
{
public void run()
{
for(int j = 1;j <= 5;j++)
{
System.out.println("\tFrom Thread B : j = " + j);
if(j==3) stop();
}
System.out.println("Exit from B ");
}
}
From Thread B
From Thread A
From Thread C
End of main Thread
From Thread A
From Thread A
From Thread A
Exit from A
From Thread C
From Thread C
From Thread C
From Thread C
Exit from C
:j=3
:i=2
:k=1
:i=3
:i=4
:i=5
:
:
:
:
k
k
k
k
=
=
=
=
2
3
4
5
join()
While isAlive() is occasionally useful, the method that you will more
commonly use to wait for a thread to finish is called join(), shown here:
final void join() throws InterruptedException
This method waits until the thread on which it is called terminates. Its
name comes from the concept of the calling thread waiting until the
specified thread joins it.
b.join(); c.join();
}
catch(InterruptedException e)
{
System.out.println("Main Thread Interrupted");
}
System.out.println("Thread One is Alive: " +
THREAD PRIORITY
1. In java, each thread is assigned a priority, which affects the order in which it is
scheduled for running.
2. The threads of the same priority are given equal treatment by the Java scheduler
and, therefore, they share the processor of a first come, first serve basis.
ThreadName.setPriority(int Number);
The intNumber is an integer value to which the threads priority is set.
The Thread class defines several priority constants:
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
The intNumber may assume one of these constants or any value
between 1 and 10. Note that the default setting is NORM_PRIORITY.
import java.lang.Thread;
class A extends Thread
{
public void run()
{
for(int i = 1;i <= 5;i++)
{
System.out.println("\tFrom Thread A : i
= " + i);
}
System.out.println("Exit from A ");
}
}
class B extends Thread
{
public void run()
{
for(int j = 1;j <= 5;j++)
{
System.out.println("\tFrom Thread B : j = " + j);
}
System.out.println("Exit from B ");
yield() method:
Thread gives up CPU for other threads ready to run
class MyThread extends Thread
{
private String name;
public MyThread(String name)
{
this.name = name;
}
public void run()
{
for (int i=0;i<10;i++) {
System.out.println(name + ": hello world");
yield();
}
}
}
public class Main3
{
public static void main(String [] args)
{
MyThread t1 = new MyThread("thread1");
MyThread t2 = new MyThread("thread2");
t1.start(); t2.start();
}
}
Race Condition:
Two or more threads need to share access to the same data.
If two threads have access to the same object and each calls to a method
that modifies the state of the object, then the threads depend on the order
in which the data were accessed, corrupted objects can result. Such a
condition is often called Race Condition.
class MyThread extends Thread
{
private String name;
public MyThread(String name)
{
this.name = name;
}
public void run()
{
for (;;)
System.out.println(name + ": hello world");
}
}
public class RaceCondition
{
public static void main(String [] args) {
MyThread t1 = new MyThread("thread1");
MyThread t2 = new MyThread("thread2");
t1.start(); t2.start();
}
}
Synchronization in Threads:
"Chettinad",
void
"College",
"of",
"and",
class SynchronizedOutput
{
public static synchronized void displayList(String name,String
list[])
{
try {
for(int i=0;i<list.length;++i)
{
System.out.println(name+list[i]);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("Interruption occured");
}
}
}
class ThreadSynchronization
{
public static void main(String args[])
{
try{
MyThread thread1 = new MyThread("Thread1:
thread1.start();
if (thread1.isAlive())
{
thread1.join();
System.out.println("Thread1 is dead.");
}
thread2.start();
if (thread2.isAlive())
{
thread2.join();
System.out.println("Thread 2 is dead.");
}
}
catch(InterruptedException e)
{
}
}
}
Output:
Thread1: Chettinad
Thread1: College
Thread1: of
Thread1: Engineering
Thread1: and
Thread1: Technology.
Thread1 is dead.
Thread2: Chettinad
Thread2: College
Thread2: of
Thread2: Engineering
Thread2: and
Thread2: Technology.
Thread 2 is dead.
APPLETS
38
What is Applets?
1. An applet is a program written in the Java programming language that can be included in an
HTML page, much in the same way an image is included in a page.
2. When you use a Java technology-enabled browser to view a page that contains an applet, the
applet's code is transferred to your system and executed by the browser's Java Virtual
Machine (JVM).
Applet Architecture
1. An applet is a window based program.
2. First, applets are event driven.
3. Event driven architecture impacts the design of an applet.
4. An applet resembles a set of interrupt service routines.
5. An applet waits until an event occurs.
6. The AWT notifies the applet about an event by calling an event handler appropriate action
and then quickly return control to the AWT.
7. Second, the user initiates interaction with an applet - not the other way around.
8. As you know, in a non - windowed program, when the program needs input, it will prompt
the user and then call some input method, such as readLine().
9. This not the way it works in an applet. Instead, the user interacts with the applet as he or she
wants, when must respond.
10. For example, when the user clicks a mouse inside the applets window, a mouse clicked
event is generated. If the user presses a key while the applets window has input focus, a
keypress event is generated.
11. Applets can contain various controls, such as push buttons and check boxes.
40
Applet Architecture . . . .
12. When the user interacts with one of these controls, an event is generated.
13. While the architecture of an applet is not as easy to understand as that of a console based
program, Javas AWT makes it as simple as possible.
14. If you have written programs for windows, you know how intimidating that environment can
be.
15. Fortunately, Javas AWT provides a much cleaner approach that is more quickly mastered.
41
Begin
Born
(Load Applet)
Initialization
start( )
stop( )
Running
Stopped
Idle
start( )
Display
paint( )
destroy( )
Destroyed
Dead
End
42
Exit of Browser
1. Initialization State
Applet enters the initialisation state when it is first loaded. This is achieved by calling the
init() method of Applet Class. The applet is born. At this stage, we may do the following, if
required,
a. Create objects needed by the applet.
b. Set up initial values
c. Load images or fonts
d. set up colors
public void init( )
{
----------------------------------------------------------------}
Action
44
2. Running State
Applets enters the running state when the system call the start () method of Applet Class.
This occurs automatically after the applet is initailized. Starting can also occur if the applet is
already in stopped state. For example, we may leave the web page containing the applet
temporarily to another page and return back to the page. This again starts the applet running.
Note that, unlike init() method, the start() method may be called more than once. We may
override the start() method to create a threa to control the applet.
Action
45
Action
46
4. Dead State
An applet is said to be dead when it is removed from memory. This occurs automatically by
invoking the destroy( ) method when we quit the browser. Like initialization, destroying
stage occurs only once in the applets life cycle. If the applet has created any resources. Like
threads we may override the destroy( ) method to clean up these resouces.
Action
47
5. Display State
Applet moves to the display state whenever it has to perform some output operations on the
screen. This happens immediately after the applet enters into the running state. The paint()
method is called to accomplish this task. Almost every applet will have a paint() method.
Like other methods in the life cycle, the default version of paint() method does absolutely
nothing. We must therefore override this method if we want anything to be displayed on the
screen.
public void paint (Graphics g)
{
--------------------------------Display Statements
--------------------------------}
48
import java.awt.*;
import java.applet.*;
/*
<applet code = "AppletDemo" width = 300 height =
300>
</applet>
*/
public class AppletDemo extends Applet
{
String msg;
public void init()
{
setBackground(Color.cyan);
}
public void start()
{
msg += "This is Start method";
}
public void stop()
{
msg += "This is Stop method";
}
public void destroy()
{
msg += "This is Destroy method";
}
public void paint(Graphics g)
{
g.drawString(msg,100,100);
}
}
Specified Colors
Specified Colors
1. Color.black
10. Color.pink
2. Color.blue
11. Color.red
3. Color.cyan
12. Color.white
4. Color.darkGray
13. Color.yellow
5. Color.gray
6. Color.green
7. Color.lightGray
8. Color.magenta
9. Color.orange
49
<HTML>
<HEAD>
<TITLE>WELCOME TO cHETTINAD</TITLE>
</HEAD>
<BODY>
<APPLET
CODE = AppletDemo.class
WIDTH = 300
HEIGHT = 200
</APPLET>
</BODY>
</HTML>
50
51
ATTRIBUTE
MEANING
CODE = AppletFileName.class
Specifies the name of the applet class to be loaded. That is, the name of the
already compiled .class file in which the executable. Java bytecode for the
applet is stored. This attribute must be specified.
CODEBASE = codebase_URL
(Optional)
Specifies the URL of the directory in which the applet resides. If the applet
resides in the same directory as the HTML file, then the CODEBASE
attirbute may be omitted entirely.
WIDTH = pixels
HEIGHT = pixels
These attributes specify the width and height of the space on the HTML
page that will be reserved for the applet.
NAME=applet_instance_name
(Optional)
A name for the applet may optionally be specified so that other applets on
the page may refer to this applet. This facilitates inter applet
communication.
ALIGN = alignment
(Optional)
This optional attribute specifies where on the page the applet will appear.
Possible values for alignment are TOP, BOTTOM, LEFT, RIGHT,
MIDDLE, ABSMIDDLE, ABSBOTTOM, TEXTTOP, AND BASELINE.
HSPACE = pixels
(Optional)
Used only when ALIGN is set to LEFT or RIGHT , this attribute specifies
the amount of horizontal blank space the browser should leave surrounding
the applet.
VSPACE = pixels
(Optional)
Used only when some vertical alignment is specified with the ALIGN
attribute (TOP, BOTTOM, etc.,) VSPACE specifes the amount of vertical
blank space the browser should leave surrounding the applet.
ALT = alternate_text
(Optional)
Non java browser will display this text where the applet would normally
go. This attribute is optional.
53
param = getParameter("fontSize");
try
{
if(param != null) //if not found
fontSize = Integer.parseInt(param);
else
fontSize = 0;
}
catch(NumberFormatException e)
{
fontSize = -1;
}
param = getParameter("leading");
try
{
if(param != null) //if not found
leading = Float.valueOf(param).floatValue();
else
leading = 0;
}
catch(NumberFormatException e)
{
leading = -1;
}
54
param = getParameter("accountEnabled");
if(param != null)
active = Boolean.valueOf(param).booleanValue();
}
public void paint(Graphics g)
{
g.drawString("Font name: " + fontName,0,10);
g.drawString("Font Size: " + fontSize,0,20);
g.drawString("Leading: " + leading, 0,42);
g.drawString("Account Active: " + active,0,58);
}
}
55
56
2. stop ( )
3. loop ( )
57
addMouseListener(this);
setBackground(Color.yellow);
soundFile1.play();
}
public void paint(Graphics g)
{
g.drawString("Click to hear a sound",20,20);
}
public void mouseClicked(MouseEvent evt)
{
soundFile2.play();
}
public void mousePressed(MouseEvent evt) {}
public void mouseReleased(MouseEvent evt) {}
public void mouseEntered(MouseEvent evt) {}
public void mouseExited(MouseEvent evt) {}
}
58
AppletStub Interface
The AppletStub interface provides a way to get information from the run-time browser
environment. The Applet class provides methods with similar names that call these
methods. Methods
public abstract boolean isActive ()
The isActive() method returns the current state of the applet. While an applet is
initializing, it is not active, and calls to isActive() return false. The system marks the
applet active just prior to calling start(); after this point, calls to isActive() return true.
public abstract URL getDocumentBase ()
The getDocumentBase() method returns the complete URL of the HTML file that loaded
the applet. This method can be used with the getImage() or getAudioClip() methods to
load an image or audio file relative to the HTML file.
public abstract URL getCodeBase ()
The getCodeBase() method returns the complete URL of the .class file that contains the
59
applet. This method can be used with the getImage() method or the getAudioClip()
60
Events
1. In the delegation model, an event is an object that describes a state change in a source.
2. It can be generated as a consequence of a person interacting with the elements in a graphical user
interface.
3. Some of the activities that cause events to be generated are pressing a button, entering a character
via the keyboard, selecting an item in a list, and clicking the mouse.
4. Event may also occur that are not directly caused by interactions with a user interface. For
example, an event may be generated when a timer expires, a counter exceeds a value, a software or
61
hardware failure occurs, or an operation is completed.
Event Sources
1. A source is an object that generates an event.
2. This occurs when the internal state of that object changes in some way.
3. Sources may generate more than one type of event.
4. A source must register listeners in order for the listeners to receive notifications about a specific
type of event.
5. Each type of event has its own registration method.
6. Here is the general form:
13. Here, Type is the name of the event and el is a reference to the event listener.
14.When such an event occurs, the registered listener is notified. This is known a s unicasting the
event.
15. A source must also provide a method that allows a listener to unregister an interest in a specific
type of event.
16. The general form of such a method is this:
public void removeTypeListener(TypeListener el)
17. Here, Type is the name of the event and el is reference to the event listener.
18. For Example, to remove a keyboard listener, you would call removeKeyListener().
19. The methods that add or remove listeners are privided by the source that generates events.
20. For example, the Component class provides methods to add and remove keyboard and mouse event
listeners.
Event Listeners
21. A Listener is an object that is notified when an event occurs. It has major requirements.
22. First, it must have been registered with one or more sources to receive notification about specific
type of events.
23. Second, it must implement methods to receive and process these notifications.
63
24. The methods that receive and pricess events are defined in a set of interfaces found in
java.awt.event.
25. For example, the MouseMotionListener interface defines two method to receive notifications when
the mouse is dragged or moved.
26. Any object may receive and process one or both of these events if it provides an implementation of
this interface.
64
EVENT CLASSES
65
Event Classes
1. The classes that represent events are at the core of Javas event handling
mechanism.
2. At the root of the Java event class hierarchy is EventObject, which is in java.util.
3. It is the superclass for all events. Its one constructor is shown here:
EventObject(Object src)
4. Here, src is the object that generates this event.
5. EventObject contains two methods: getSource() and toString().
6. The getSource() method returns the source of the event.
7. Its general form is shown here:
Object getSource()
8. As expected, toString() returns the string equivalent of the event.
9. The AWTEvent, defined within the java.awt package, is a subclass of EventObject.
10. It is the superclass of all AWT based events used by the delegation event model.
11. Its getID() method can be used to determine the type of the event. The signature of
this method is shown here:
int getID()
66
The package java.awt.event defines several types of events that are generated by
various user interface elements.
EVENT CLASSES
DESCRIPTION
ActionEvent
AdjustmentEvent
ComponentEvent
ContainerEvent
FocusEvent
InputEvent
ItemEvent
Generated when a check box or list item is clicked; also occurs when a choice
selection is made or a checkable menu item is selected or deselecte.
KeyEvent
MouseEvent
MouseWheelEvent
TextEvent
WindowsEvent
70
71
73
74
if(ls.getSelectedIndex() == 3)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x * y; tf3.setText(String.valueOf(z));
}
if(ls.getSelectedIndex() == 4)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x / y; tf3.setText(String.valueOf(z));
}
if(ls.getSelectedIndex() == 5)
{
tf1.setText(""); tf2.setText(""); tf3.setText("");
}
if(ls.getSelectedIndex() == 6)
{
int a = ch.getItemCount(); tf3.setText(String.valueOf(a));
}
if(ls.getSelectedIndex() == 7)
{
tf3.setText(ch.getItem(ch.getSelectedIndex()));
75
}
}
You can obtain the command name for the invoking ActionEvent object by using the
getActionCommand() method, shown here:
String getActionCommand()
For example, when a button is pressed, and action event is generated that has a command name equal
to the label on that button.
The getModifiers() method returns a value that indicates which modifier keys(ALT,CTRL,META and
SHIFT) were pressed when the event was generated. Its form is shown here:
String getModifiers()
79
80
if(sbh.getValue() == 150)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x * y;
tf3.setText(String.valueOf(z));
}
if(sbh.getValue() == 200)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x / y;
tf3.setText(String.valueOf(z));
}
if(sbh.getValue() == 250)
{
tf1.setText("");
}
}
}
tf2.setText("");
tf3.setText("");
81
COMPONENT_RESIZED
COMPONENT_SHOWN
of
The getComponent() method returns the component that generated the event.
It is shown here:
82
Component getComponent()
A FocusEvent is generated when a component gains or loses input focus. These events are
identified by the integer constants FOCUS_GAINED and FOCUS_LOST
FocusEvent is a subclass of ComponentEvent and has threse constructor:
FocusEvent(Component src, int type)
FocusEvent(Component src, int type, boolean temporaryFlag)
FocusEvent(Component src, int type, boolean temporaryFlag, Component other)
1. Here, src is a reference to the component that generated this event.
2. The type of the event is specified by type.
3. The argument temporaryFlag is set to true if the focus event is temporary.
4. Otherwise, it is set to false.
5. The other component involved in the focus change, called the apposite component, is passed in
other.
6. Therefore, if a FOCUS_GAINED event occurred, other will refer to the component that lost
focus.
7. Conversely, if a FOCUS_LOST event occurred, other will refer to the component that gains
focus.
84
import java.applet.*;
FocusEvent Example Focus Gained and Focus Lost in TextBox
import java.awt.*;
import java.awt.event.*;
/*
<applet code="Focus_Event.class" height=300 width=1000>
</applet>
*/
public class Focus_Event extends Applet implements FocusListener
{
TextField tf1,tf2,tf3;
public void init()
{
setBackground(Color.red);
setForeground(Color.green);
add(tf3);
tf1.addFocusListener(this);
tf2.addFocusListener(this);
85
86
MOUSE_DRAGGED
MOUSE_ENTERED
MOUSE_EXITED
MOUSE_MOVED
MOUSE_PRESSED
MOUSE_RELEASED
MOUSE_WHEEL
87
Description
These retrun the X and Y coordinates of the mouse when the event
occured
Point getPoint()
getClickCount()
The methods obtains the number of mouse clicks for this event
isPopupTrigger()
import java.awt.*;
MouseEvent Example
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Mouse" width=500 height=500>
</applet>
*/
public class Mouse extends Applet implements MouseListener,MouseMotionListener
{
int X=0,Y=20;
String msg="MouseEvents";
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
setBackground(Color.black);
setForeground(Color.red);
}
public void mouseEntered(MouseEvent m)
{
setBackground(Color.magenta);
showStatus("Mouse Entered");
repaint();
}
public void mouseExited(MouseEvent m)
{
setBackground(Color.black);
showStatus("Mouse Exited");
repaint();
}
in Mouse
89
90
91
Methods
Description
int getWheelRotation()
It returns the number of rotational units. If the value is positive, the wheel
moved conterclockwise. If the value is negative, the wheel moved
clockwise.
int getScrollType()
int getScrollAmount()
BUTTON2_MASK
BUTTON3_MASK
SHIFT_MASK
BUTTON1_MASK
CTRL_MASK
META_MASK
93
BUTTON2_DOWN_MASK
BUTTON3_DOWN_MASK
SHIFT_DOWN_MASK
BUTTON1_DOWN_MASK
CTRL_DOWN_MASK
META_DOWN_MASK
5. When writing new code, it is recommended that you use the new, extended modifiers
rather that the original modifiers.
6. To test if a modifier was pressed at the time an event is generated, use the
isAltDown(), isAltGraphDown(), isControlDown(), isMetaDown(), and isShiftDown()
methods.
7. The forms of these methods are shown here:
boolean isAltDown()
boolean isAltGraphDown()
boolean isControlDown()
boolean isMetaDown()
boolean isShiftDown()
94
You can obtain a value that contains all of the original modifer flags by calling the
getModifiers() method. It is shown here:
int getModifiers()
You can obtain the extended modifiers by called getModifiersEx(), which is shown here:
int getModifiersEx()
SELECTED
95
96
import java.applet.*;
ItemEvent Example in Checkbox
import java.awt.*;
import java.awt.event.*;
/*
<applet code="Checkbox_Setnull.class" height=300 width=1000>
</applet>
*/
public class Checkbox_Setnull extends Applet implements ItemListener
{
TextField tf1,tf2,tf3;
Label l1,l2,l3;
Checkbox ch1,ch2,ch3,ch4,ch5;
int x,y,z;
public void init()
{
setBackground(Color.red);
setForeground(Color.green);
setLayout(null);
l1 = new Label("Enter the A Value");
l1.setBounds(0,0,100,25);
l2 = new Label("Enter the B Value");
l2.setBounds(0,50,100,25);
l3 = new Label("Addition of the Two Numbers");
l3.setBounds(0,100,170,25);
97
98
99
if(ch3.getState()==true)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x * y;
tf3.setText(String.valueOf(z));
}
if(ch4.getState()==true)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x / y;
tf3.setText(String.valueOf(z));
}
if(ch5.getState()==true)
{
tf1.setText("");
}
}
}
tf2.setText("");
tf3.setText("");
100
import java.applet.*;
ItemEvent Example in CheckboxGroup
import java.awt.*;
import java.awt.event.*;
/*
<applet code="Checkboxgroup_Setnull.class" height=300 width=1000>
</applet>
*/
public class Checkboxgroup_Setnull extends Applet implements ItemListener
{
TextField tf1,tf2,tf3;
Label l1,l2,l3;
Checkbox ch1,ch2,ch3,ch4,ch5;
CheckboxGroup cbg;
int x,y,z;
public void init()
{
setBackground(Color.red);
setForeground(Color.green);
setLayout(null);
cbg = new CheckboxGroup();
l1 = new Label("Enter the A Value");
l1.setBounds(0,0,100,25);
l2 = new Label("Enter the B Value");
l2.setBounds(0,50,100,25);
101
l3 = new Label("Compute the Two Numbers");
l3.setBounds(0,100,170,25);
102
103
if(ch3.getState()==true)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x * y;
tf3.setText(String.valueOf(z));
}
if(ch4.getState()==true)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x / y;
tf3.setText(String.valueOf(z));
}
if(ch5.getState()==true)
{
tf1.setText("");
}
}
}
tf2.setText("");
tf3.setText("");
104
106
107
if(ch.getSelectedIndex() == 3)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x * y; tf3.setText(String.valueOf(z));
}
if(ch.getSelectedIndex() == 4)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x / y; tf3.setText(String.valueOf(z));
}
if(ch.getSelectedIndex() == 5)
{
tf1.setText(""); tf2.setText(""); tf3.setText("");
}
if(ch.getSelectedIndex() == 6)
{
int a = ch.getItemCount(); tf3.setText(String.valueOf(a));
}
if(ch.getSelectedIndex() == 7)
{
tf3.setText(ch.getItem(ch.getSelectedIndex()));
108
}
}
VK_ESCAPE
VK_CANCEL
VK_UP
VK_DOWN
VK_LEFT
VK_RIGHT
VK_PAGE_DOWN
VK_PAGE_UP
VK_SHIFT
VK_ALT
VK_CONTROL
109
9. The VK constants specify virtual key codes and are independent of any modifiers,
such as control, shift, or alt. KeyEvent is a subclass of InputEvent.
10. Here are two of its constructors:
KeyEvent(Component src, int type, long when, int modifiers, int code)
KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)
11. Here, src is a reference to the component that generated the event.
12. The type of the event is specified by type.
13. The system time at which the key was pressed is passed in when.
14. The modifiers argument indicates which modifiers where pressed when this key
event occurred.
15. The virutal key code, such as VK_UP, VK_A, and so forth, is passed in code.
16. The character equivalent is passed in ch. If no valid character exists, then ch
contains CHAR_UNDEFINED.
17. For KEY_TYPED events, code will contain VK_UNDEFINED.
18. The KeyEvent class defines several methods, but the most commonly used ones are
getKeyChar(), which returns the character that was entered, and getKeyCode(), which
110
returns the key code.
111
Here, src is a reference to the object that generated this event. The type of the event is
specified by type.
112
import java.applet.*;
TextEvent Example in Textbox
import java.awt.*;
import java.awt.event.*;
/*
<applet code="Text_Event.class" height=300 width=1000>
</applet>
*/
public class Text_Event extends Applet implements TextListener
{
TextField tf1,tf2,tf3;
public void init()
{
setBackground(Color.red);
setForeground(Color.green);
tf1 = new TextField(10);
tf1.setBounds(200,0,100,25);
tf2 = new TextField(10);
tf2.setBounds(200,50,100,25);
tf3 = new TextField(10);
tf3.setBounds(200,100,100,25);
add(tf1);
add(tf2);
add(tf3);
tf1.addTextListener(this);
tf2.addTextListener(this);
}
public void textValueChanged(TextEvent te)
{
tf3.setText(tf1.getText());
113
}
}
WINDOW_CLOSED
WINDOW_CLOSING
WINDOW_DEACTIVATED
WINDOW_DEICONIFIED
WINDOW_GAINED_FOCUS
WINDOW_ICONIFIED
WINDOW_LOST_FOCUS
WINDOW_OPENED
WINDOW_STATE_CHANGED
114
The most commonly used method in this class is getWindow(). It returns the Window
object that generated the event. Its general form is shown here:
Window getWindow()
115
Event Classes
ActionEvent
ActionListener
AdjustmentEvent
AdjustmentListener
ComponentEvent
ComponentListener
ContainerEvent
ContainerListener
FocusEvent
FocusListener
ItemEvent
ItemListener
KeyEvent
KeyListener
MouseEvent
MouseListener
MouseMotionListener
InputEvent
116
Event Classes
MouseWheelEvent
MouseWheelListener
TextEvent
TextListener
WindowEvent
WindowsListener
WindowFocusListener
117
Sources of Events
Event Source
Description
Button
Checkbox
Choice
List
Menu Item
Scrollbar
Text components
Window
118
APPLET CONTROLS
119
120
Networking
121
Networking
Socket
A socket is bound to a port number so that the TCP layer can identify the
correct application for data
Ports
Many different services can be running on the host. A port identifies a service
within a host
Many standard port numbers are pre-assigned time of day 13, ftp 21, telnet 23,
smtp 25, http 80
IP address + port number = "phone number for service
protocols : rules that facilitate communications between machines
Examples:
1.HTTP: HyperText Transfer Protocol
2.FTP: File Transfer Protocol
3.SMTP: Simple Message Transfer Protocol
4.TCP: Transmission Control Protocol
5.UDP: User Datagram Protocol, good for, e.g., video delivery)
122
Protocols are standardized and documented. So machines can reliably work
with one another
Networking
Client-Server interaction
Communication between hosts is two-way, but usually the two hosts take
different roles
Server
Server waits for client to make request
Server registered on a known port with the host ("public phone number")
Usually running in endless loop
Listens for incoming client connections
Server offers shared resource (information,database, files, printer, compute
power) to clients
Client
Client "calls" server to start a conversation
Client making calls uses hostname/IP address and port number
Sends request and waits for response
Standard services always running ftp, http, smtp, etc. server running on
123
host using expected port
OutputStream
InputStream
Client
Server
InputStream
OutputStream
124
Client/Server Communications
The server must be running when a client
starts. The server waits for a connection request
from a client. To establish a server, you need to
create a server socket and attach it to a port,
which is where the server listens for
connections.
Server Host
Server socket on port 8000
SeverSocket server =
new ServerSocket(8000);
Client Host
I/O Stream
A client socket
Socket socket =
server.accept()
After a server
socket is
created, the
server can use
this statement
to listen for
connections.
Client socket
Socket socket =
new Socket(host, 8000)
125
Networking Communication
TCP
- Transmission Control Protocol
Protocols
Reliable - When TCP segments, the smallest unit of TCP transmissions, are
lost or corrupted, the TCP implementation will detect this and retransmit
necessary segments
Connection-oriented - TCP sets up a connection before transmission of any
data
Continuous Stream - TCP provides a communication medium that allows for
an arbitrary number of bytes to be sent and received smoothly
126
Networking
Occasionally, you would like to know who is connecting to the server. You
can use the InetAddress class to find the client's host name and IP
address. The InetAddress class models an IP address. You can use the
statement shown below to create an instance of InetAddress for the client
on a socket.
InetAddress inetAddress = socket.getInetAddress();
Next, you can display the client's host name and IP address, as follows:
System.out.println("Client's host name is " +
inetAddress.getHostName());
System.out.println("Client's IP Address is " +
inetAddress.getHostAddress());
127
The
Socket
Server Socket
DatagramSocket and
MulticastSocket
128
UDP Client
import java.net.*;
import java.io.*;
class UDPClient
{
publicstaticvoid main(String args[]) throws Exception
{
DatagramSocket dsoc=new DatagramSocket(24);
byte buff[]=newbyte[1024];
DatagramPacket dpack=new DatagramPacket(buff,buff.length);
dsoc.receive(dpack);
System.out.println(new String(dpack.getData()));
}
}
129
UDP Server
import java.net.*;
import java.io.*;
import java.util.*;
class UDPServer
{
publicstaticvoid main(String args[]) throws Exception
{
DatagramSocket dsoc=new DatagramSocket(5217);
InetAddress host=InetAddress.getLocalHost();
String str=(new Date()).toString();
byte buf[]=str.getBytes();
dsoc.send(new DatagramPacket(buf,buf.length,host,24));
dsoc.close();
}
}
130
TCP
- Simple-Server Example
The server creates a server socket that listen on the port given on the command
line. It then enters infinite loop doing the following: when a connection with a client
is established it reads some input from the client (terminated with a 0 byte), sends
back the message Simon says: plus the input received, and closes the connection.