0% found this document useful (0 votes)
13 views63 pages

Java Applets and Multithreading Guide

The document provides an overview of Java programming concepts, focusing on applets, event handling, GUI programming, and multithreading. It explains the lifecycle of applets, differences between applets and applications, and the advantages of multithreading in Java. Additionally, it covers thread creation, thread priorities, synchronization, and inter-thread communication, along with examples and explanations of key methods and classes used in Java programming.

Uploaded by

chavanshaifali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views63 pages

Java Applets and Multithreading Guide

The document provides an overview of Java programming concepts, focusing on applets, event handling, GUI programming, and multithreading. It explains the lifecycle of applets, differences between applets and applications, and the advantages of multithreading in Java. Additionally, it covers thread creation, thread priorities, synchronization, and inter-thread communication, along with examples and explanations of key methods and classes used in Java programming.

Uploaded by

chavanshaifali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

INTRODUCTION TO JAVA PROGRAMMING

UNIT-IV
Applets – Concepts of Applets, differences between applets and applications, life cycle of an
applet, types of applets, creating applets, passing parameters to applets.
Event Handling: Events, Handling mouse and keyboard events, Adapter classes.
Files- Streams- Byte streams, Character streams, Text input/output.

UNIT-V
GUI Programming with Java – AWT class hierarchy, component, container, panel, window, frame,
graphics.
AWT controls: Labels, button, text field, check box, and graphics.
Layout Manager – Layout manager types: border, grid and flow.
Swing – Introduction, limitations of AWT, Swing vs AWT
Multithreading

Multithreading in java is a process of executing multiple threads simultaneously.

Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and


multithreading, both are used to achieve multitasking.

But we use multithreading than multiprocessing because threads share a common memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.

Java Multithreading is mostly used in games, animation etc.

Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can
performmultiple operations at sametime.

2) You can perform many operations together so it savestime.

3) Threads are independent so it doesn't affect other threads if exception occur in a singlethread.

Life cycle of a Thread (Thread States)

A thread can be in one of the five states. According to sun, there is only 4 states in thread life
cycle in java new, runnable, non-runnable and terminated. There is no running state.

But for better understanding the threads, we are explaining it in the 5 states.

The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable(Blocked)
5. Terminated

JAVA PROGRAMMING Page 2


JAVA PROGRAMMING Page 3
How to create thread

There are two ways to create a thread:

1. By extending Threadclass
2. By implementing Runnableinterface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a
[Link] class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:

oThread()
oThread(String
name)
oThread(Runnable r)
oThread(Runnable r,String name)

JAVA PROGRAMMING Page 4


Commonly used methods of Thread class:

1. public void run(): is used to perform action for athread.


2. public void start(): starts the execution of the [Link] calls the run() method onthethread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number ofmilliseconds.
4. public void join(): waits for a thread todie.
5. public void join(long miliseconds): waits for a thread to die for the specifiedmiliseconds.
6. public int getPriority(): returns the priority of thethread.
7. public int setPriority(int priority): changes the priority of thethread.
8. public String getName(): returns the name of thethread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executingthread.
11. public int getId(): returns the id of thethread.
12. public [Link] getState(): returns the state of thethread.
13. public boolean isAlive(): tests if the thread isalive.
14. public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads toexecute.
15. public void suspend(): is used to suspend thethread(depricated).
16. public void resume(): is used to resume the suspendedthread(depricated).
17. public void stop(): is used to stop thethread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemonthread.
19. public void setDaemon(boolean b): marks the thread as daemon or userthread.
20. public void interrupt(): interrupts thethread.
21. public boolean isInterrupted(): tests if the thread has beeninterrupted.
22. public static boolean interrupted(): tests if the current thread has beeninterrupted.

Runnable interface:

The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().
1. public void run(): is used to perform action for athread.

Starting a thread:

start() method of Thread class is used to start a newly created thread. It performs following
tasks:
oA new thread starts(with new callstack).
oThe thread moves from New state to the Runnable state.
oWhen the thread gets a chance to execute, its target run() method will run.

JAVA PROGRAMMING Page 5


Java Thread Example by extending Thread

class classMulti extends Thread{


public void run()
{ [Link]("thread is running...");
}
public static void main(String args[])
{ Multi t1=new Multi();
[Link]();
}}
Output:thread isrunning...

Java Thread Example by implementing Runnable interface

class Multi3 implements Runnable{


public void run()
{ [Link]("thread is running...");
}
public static void main(String args[])
{ Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
[Link]();
}}
Output:thread isrunning...

Priority of a Thread (Thread Priority):


Each thread have a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread schedular schedules the threads according to their priority (known as preemptive
scheduling). But it is not guaranteed because it depends on JVM specification that which
scheduling it chooses.

3 constants defined in Thread class:

1. public static intMIN_PRIORITY


2. public static intNORM_PRIORITY
3. public static intMAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and


the value of MAX_PRIORITY is 10.

Example of priority of a Thread:


class TestMultiPriority1 extends
Thread{public void run(){
[Link]("running thread name is:"+[Link]().getName());
[Link]("running thread priority is:"+[Link]().getPriority());
}
public static void main(String args[]){

JAVA PROGRAMMING Page 6


TestMultiPriority1 m1=newTestMultiPriority1();
TestMultiPriority1 m2=newTestMultiPriority1();
[Link](Thread.MIN_PRIORITY);
[Link](Thread.MAX_PRIORITY);
[Link]();
[Link]();
}}
Output:running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1

Java synchronized method


If you declare any method as synchronized, it is known as synchronized method.

Synchronized method is used to lock an object for any 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.

Example of inter thread communication in java


Let's see the simple example of inter thread communication.

classCustomer{ intamo
unt=10000;
synchronized void withdraw(int amount){
[Link]("going to withdraw...");
if([Link]<amount){
[Link]("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
[Link]-=amount;
[Link]("withdraw completed...");
}
synchronized void deposit(int amount)
{ [Link]("going to deposit...");
[Link]+=amount;
[Link]("deposit completed... ");
notify();
}
}
classTest{
public static void main(String args[])
{ final Customer c=newCustomer();
new Thread(){
public void run(){[Link](15000);}
}.start();
newThread(){

JAVA PROGRAMMING Page 7


public void run(){[Link](10000);}
}
start();
}}
Output: going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
ThreadGroup in Java
Java provides a convenient way to group multiple threads in a single object. In such way, we can
suspend, resume or interrupt group of threads by a single method call.

Note: Now suspend(), resume() and stop() methods are deprecated.

Java thread group is implemented by [Link]

[Link] of ThreadGroup class

There are only two constructors of ThreadGroup class.

ThreadGroup(String name)
ThreadGroup(ThreadGroup parent, String name)

Let's see a code to group multiple threads.

1. ThreadGroup tg1 = new ThreadGroup("GroupA");


2. Thread t1 = new Thread(tg1,newMyRunnable(),"one");
3. Thread t2 = new Thread(tg1,newMyRunnable(),"two");
4. Thread t3 = new Thread(tg1,newMyRunnable(),"three");

Now all 3 threads belong to one group. Here, tg1 is the thread group name, MyRunnable is the
class that implements Runnable interface and "one", "two" and "three" are the thread names.

Now we can interrupt all threads by a single line of code only.

1. [Link]().getThreadGroup().interrupt();

JAVA PROGRAMMING Page 8


UNIT 4

UNIT IV: Applets – Concepts of Applets, differences between applets and


applications, life cycle of an applet, types of applets, creating applets, passing parameters to
applets.
Event Handling- Events, Event sources, Event classes, Event Listeners, Delegation event
model, handling mouse and keyboard events, Adapter classes.
Streams- Byte streams, Character streams, Text input/output.

APPLETS:
An applet is a program that comes from server into a client and gets executed at client side and
displays the result.
An applet represents byte code embedded in a html page. (Applet = bytecode + html) and run with
the help of Java enabled browsers such as Internet Explorer.
An applet is a Java program that runs in a browser. Unlike Java applications applets do not have a
main () method.
To create applet we can use [Link] or [Link] class. All applets inherit the
super class „Applet‟. An Applet class contains several methods that help to control the execution
of an applet.
Advantages:
 Applets provide dynamic nature for a webpage.
 Applets are used in developing games and animations.
 Writing and displaying (browser) graphics and animations is easier than
applications.
 In GUI development, constructor, size of frame, window closing code etc. are not
required

Restrictions of Applets of Applets Vs Applications


 Applets are required separate compilation before opening in a browser.
 In realtime environment, the bytecode of applet is to be downloaded from the server to
the client machine.
 Applets are treated as untrusted (as they were developed by unknown people and placed
on unknown servers whose trustworthiness is not guaranteed).
 Extra Code is required to communicate between applets using

AppletContext. DEFFERENCES BETWEEN APPLETS AND


FEATURE
APPLICATIONS APPLICATION APPLET
main() method main() method Present main() method Not present

Execution Can be executed on standalone Used to run a program on client


computer system. (JDK & JRE) Browser like Chrome.

Nature Called as stand-alone Requires some third party tool


application as application can help like a browser to execute
be executed from command
AVA PROGRAMMING prompt
Restrictions Can access any data or Cannot access anything on the
software system except browser‟s
available on the system services

Security Does not require any security Requires highest security for the
system as they are untrusted

Programming larger programs small programs

Platform platform independent platform independent

Accessibility The java applications are Applets are designed just for
designed to work with the handling the client site
client as well as server. problems.

Working Applications are created by Applets are created by


writing public static void extending [Link]
main(String[] s) method class

Client side / The applications don't Applets are designed for the
Server side have such type of criteria client site programming purpose

Methods Application has a single start Applet application has 5


point which is main method methods which will be
automatically invoked.

Example
public class MyClass import [Link].*;
{ import [Link].*;
public static void main(String
args[]) {} public
} class Myclass extends Applet
{
public void init()
{
}
public void start()
{
}
public void stop()
{
}
public void destroy() {}

public void paint(Graphics g) {}


}
LIFE CYCLE OF AN APPLET
Let the Applet class extends Applet or JApplet class.

Initialization:

public void init(): This method is used for initializing variables, parameters to create
components. This method is executed only once at the time of applet loaded into memory.
public void init()
{
//initialization
}
Runnning:

public void start (): After init() method is executed, the start method is executed
automatically. Start method is executed as long as applet gains focus. In this method code
related to opening files and connecting to database and retrieving the data and processing
the data is written.
Idle / Runnable:

public void stop (): This method is executed when the applet loses focus. Code related to
closing the files and database, stopping threads and performing clean up operations are
written in this stop method.
Dead/Destroyed:

public void destroy (): This method is executed only once when the applet is terminated
from the memory.
Executing above methods in that sequence is called applet life cycle.
We can also use public void paint (Graphics g) in applets.
//An Applet skeleton.
import [Link].*;
import [Link].*;
/*
<applet code="AppletSkel" width=300 height=100>
</applet>
*/
public class AppletSkel extends Applet {
3 Called first.
public
void init()
{
4 initialization
}
/* Called second, after init(). Also called whenever the applet is restarted. */
public void start() {
3 start or resume execution
}
4 Called when the applet is
stopped. public void stop()
{
5 suspends execution
}
/* Called when applet is terminated. This is the last method executed. */
public void destroy() {
5 perform shutdown activities
}
6 Called when an applet's window must
be restored. public void paint(Graphics
g) {
7 redisplay contents of window
}
}
After writing an applet, an applet is compiled in the same way as Java application but running of
an applet is different.
There are two ways to run an applet.

Executing an applet within a Java compatible web browser.

Executing an applet using „appletviewer‟. This executes the applet in a window.

To execute an applet using web browser, we must write a small HTML file which contains the
appropriate „APPLET‟ tag. <APPLET> tag is useful to embed an applet into an HTML page. It
has the following form:
<APPLET CODE=”name of the applet class file” HEIGHT = maximum height of applet in
pixels WIDTH = maximum width of applet in pixels ALIGN = alignment (LEFT, RIGHT,
MIDDLE, TOP, BOTTOM)>
<PARAM NAME = parameter name VALUE = its
value> </APPLET>
Execution: appletviewer [Link] or appletviewer [Link]
The <PARAM> tag useful to define a variable (parameter) and its value inside the HTML page
which can be passed to the applet. The applet can access the parameter value using
getParameter () method, as: String value = getParameter (“pname”);
Example Program:
Following is a simple applet named [Link] −
import [Link].*; import [Link].*;
public class HelloWorldApplet extends Applet {
public void paint (Graphics g) { [Link] ("Hello World", 25, 50);
}}
Invoking an Applet - [Link]
<html>
<title>The Hello, World Applet</title>
<applet code = "[Link]" width = "320" height = "120">
</applet>
</html>

OUTPUT: javac [Link]


appletviewer [Link]
Embedded an Applet
//[Link]
import [Link];
import [Link];
/*
<applet code="[Link]" width="300" height="300">
</applet>
*/
public class First extends Applet
{
public void paint(Graphics g)
{ [Link]("welcome to applet",150,150);
}
}
OUTPUT: javac [Link]
appletviewer [Link]

TYPES OF APPLETS
Applets are of two types:
// Local Applets
// Remote Applets
Local Applets: An applet developed locally and stored in a local system is called local applets.
So, local system does not require internet. We can write our own applets and embed them into
the web pages.
Remote Applets: The applet that is downloaded from a remote computer system and embed
applet into a web page. The internet should be present in the system to download the applet and
run it. To download the applet we must know the applet address on web known as Uniform
Resource Locator(URL) and must be specified in the applets HTML document as the value of
CODEBASE.
PASSING PARAMETERS TO AN APPLET
Java applet has the feature of retrieving the parameter values passed from the html page. So, you
can pass the parameters from your html page to the applet embedded in your page. The param
tag(<parma name="" value=""></param>) is used to pass the parameters to an applet. The
applet has to call the getParameter() method supplied by the [Link] parent class.

Ex1: Write a program to pass employ name and id number to an applet.


import [Link].*;
import [Link].*;
/* <applet code="[Link]" width = 600 height= 450>
<param name = "t1" value="Hari Prasad"> <param name
= "t2" value ="101">
</applet> */

public class MyApplet2 extends Applet


{
String n;
String id;
public void init()
{
n = getParameter("t1");
id = getParameter("t2");
}
public void paint(Graphics g)
{
rawString("Name is : "
+ n, 100,100);
[Link]("Id is :
"+ id, 100,150);
}
}
Ex2: Write a program to pass two numbers and pass result to an applet.
import [Link].*;
import [Link].*;
/*<APPLET code="Pp" width="300"
height="250"> <PARAM name="a" value="5">
<PARAM name="b" value="5">
</APPLET>*/
public class Pp extends Applet
{
String str;
int a,b,result;
public void init()
{
str=getParameter("a");
a=[Link](str);
str=getParameter("b");
b=[Link](str);
result=a+b;
str=[Link](result);
}
public void paint(Graphics g)
{
[Link](" Result of Addition is : "+str,0,15);
}
}

Ex3: [Link]
import [Link].*;
import [Link].*;
/*<Applet code="hai" height="250" width="250">
<PARAM name="Message" value="Hai friend how are you ..?"></APPLET>
*/
class hai extends Applet
{
private String defaultMessage = &quot;Hello!&quot;;
public void paint(Graphics g) {

String inputFromPage = [Link](&quot;Message&quot;); if


(inputFromPage == null) inputFromPage = defaultMessage;
[Link](inputFromPage, 50, 55);
}
}
Output:
EVENT HANDLING
Event handling is at the core of successful applet programming. Most events to which the applet
will respond are generated by the user. The most commonly handled events are those generated
by the mouse, the keyboard, and various controls, such as a push button.
Events are supported by the [Link] package.

The Delegation Event Model



The modern approach to handling events is based on the delegation event model, which
defines standard and consistent mechanisms to generate and process events.

Its concept is quite simple: a source generates an event and sends it to one or
more listeners. In this scheme, the listener simply waits until it receives an event. Once
received, the listener processes the event and then returns.

The advantage of this design is that the application logic that processes events is
cleanly separated from the user interface logic that generates those events. A user interface
element is able to "delegate" the processing of an event to a separate piece of code.

In the delegation event model, listeners must register with a source in order to
receive an event notification. This provides an important benefit: notifications are sent only
to listeners that want to receive them.

EVENTS
In the delegation model, an event is an object that describes a state change in a source. It can be
generated as a consequence of a person interacting with the elements in a graphical user
interface. 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.
Events 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,
software or hardware failure occurs, or an operation is completed.
EVENT SOURCES
A source is an object that generates an event. This occurs when the internal state of that object
changes in some way. Sources may generate more than one type of event. A source must register
listeners in order for the listeners to receive notifications about a specific type of event. Each
type of event has its own registration method.
Here is the general form:
public void add Type Listener( Type Listener el )
EVENT LISTENERS
A listener is an object that is notified when an event occurs. It has two major requirements. First,
it must have been registered with one or more sources to receive notifications about specific
types of events. Second, it must implement methods to receive and process these notifications.
The methods that receive and process events are defined in a set of interfaces found in
[Link].
For example, the MouseMotionListener interface defines two methods to receive notifications
when the mouse is dragged or moved.
EVENT CLASSES
The classes that represent events are at the core of Java's event handling mechanism. At the root
of the Java event class hierarchy is EventObject, which is in [Link]. It is the superclass for all
events.
It’s one constructor is shown here:
EventObject(Object src )
EventObject contains two methods: getSource( ) and toString( ) .
The getSource( ) method returns the source of the event. Ex: Object getSource( )
toString( ) returns the string equivalent of the event.
The package [Link] defines several types of events that are generated by various user
interface elements.
Event Class Description
ActionEvent Generated when a button is pressed, a list item is double-clicked, or a menu
item is selected.
AdjustmentEvent Generated when a scroll bar is manipulated.
ComponentEvent Generated when a component is hidden, moved, resized or becomes visible.
ContainerEvent Generated when a component is added to or removed from a container.
FocusEvent Generated when a component gains or loses keyboard focus.
InputEvent Abstract super class for all component input event classes.
ItemEvent Generated when a check box or list item is clicked; so occurs when a choice
selection is made or a checkable menu item is selected or deselected.
KeyEvent Generated when input is received from the keyboard.
MouseEvent Generated when the mouse is dragged, moved, clicked, pressed, or released;
also generated when the mouse enters or exits a component.
MouseWheelEvent Generated when the mouse wheel is moved. (Added by Java 2, version 1.4)
TextEvent Generated when the value of a text area or text field is changed.
WindowEvent Generated when a window is activated, closed, deactivated, deiconified,
iconified, opened, or quit.

The ActionEvent Class


An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a menu
item is selected. The ActionEvent class defines four integer constants that can be used to
identify any modifiers associated with an action event: ALT_MASK , CTRL_MASK ,
META_MASK , and SHIFT_MASK .
ActionEvent has these three constructors:
ActionEvent(Object src , int type , String cmd )
ActionEvent(Object src , int type , String cmd , int modifiers )
ActionEvent(Object src , int type, String cmd, long when , int modifiers )
The ComponentEvent Class
// ComponentEvent is generated when the size, position, or visibility of a component is
changed. There are four types of component events. The constants and their meanings are
shown here:
COMPONENT_HIDDEN The component was hidden.
COMPONENT_MOVED The component was moved.
COMPONENT_RESIZED The component was resized.
COMPONENT_SHOWN The component became visible.
The ContainerEvent Class
//ContainerEvent is generated when a component is added to or removed from a container.
There are two types of container events.

COMPONENT_ADDED and
COMPONENT_REMOVED The KeyEvent Class
//KeyEvent is generated when keyboard input occurs. There are three types of key events,
which are identified by these integer constants: KEY_PRESSED, KEY_RELEASED,
and KEY_TYPED .
The first two events are generated when any key is pressed or released. The last event occurs
only when a character is generated.
The MouseEvent Class
There are eight types of mouse events. The MouseEvent class defines the following integer
constants that can be used to identify them:
MOUSE_CLICKED The user clicked the mouse.
MOUSE_DRAGGED The user dragged the mouse.
MOUSE_ENTERED The mouse entered a component.
MOUSE_EXITED The mouse exited from a
component. MOUSE_MOVED The mouse moved.
MOUSE_PRESSED The mouse was pressed.
MOUSE_RELEASED The mouse was released.
MOUSE_WHEEL The mouse wheel was moved (Java 2,
v1.4).
The WindowEvent Class
There are ten types of window events. The WindowEvent class defines integer constants that
can be used to identify them. The constants and their meanings are shown here:
WINDOW_ACTIVATED The window was activated.
WINDOW_CLOSED The window has been closed.
WINDOW_CLOSING The user requested that the window beclosed.
WINDOW_DEACTIVATED The window was deactivated.
WINDOW_DEICONIFIED The window was deiconified.
WINDOW_GAINED_FOCUS The window gained input
focus. WINDOW_ICONIFIED The window was iconified.
WINDOW_LOST_FOCUS The window lost input
focus. WINDOW_OPENED The window was opened.
WINDOW_STATE_CHANGED The state of the window changed.
EVENT LISTENER INTERFACES
When an event occurs, the event source invokes the appropriate method defined by the listener
and provides an event object as its argument
Interface Description
ActionListener Defines one method to receive action events.
AdjustmentListener Defines one method to receive adjustment events.
ComponentListener Defines four methods to recognize when a component is hidden,
moved, resized, or shown.
ContainerListener Defines two methods to recognize when a component is added to or
removed from a container.
FocusListener Defines two methods to recognize when a component gains or losses
keyboard focus.
ItemListener Defines one method to recognize when the state of an item changes.
KeyListener Defines three methods to recognize when a key is pressed, released,
or typed.
MouseListener Defines five methods to recognize when the mouse is clicked, enters a
component, exits a component, is pressed, or is released.
MouseMotionListener Defines two methods to recognize when the mouse is dragged or
moved.
MouseWheelListener Defines one method to recognize when the mouse wheel is moved.
TextListener Defines one method to recognize when a text value changes.
WindowListener Defines seven methods to recognize when a window is activated,
closed, deactivated, deiconified, iconified, opened, or quit.
The delegation event model has two parts: sources and listeners. Listeners are created by
implementing one or more of the interfaces defined by the [Link] package.
The ActionListener Interface
This interface defines the actionPerformed( ) method that is invoked when an action event
occurs.
Its general form is shown here: void actionPerformed(ActionEvent ae )
The ItemListener Interface
This interface defines the itemStateChanged( ) method that is invoked when the state of an item
changes.
Its general form is shown here: void itemStateChanged(ItemEvent ie )
The KeyListener Interface
This interface defines three methods. The keyPressed( ) and keyReleased( ) methods are invoked
when a key is pressed and released, respectively. The keyTyped( ) method is invoked
when a character has been entered. For example, if a user presses andreleases the key,
three events are generated in A sequence: key pressed, typed, and released.
The general forms of these methods are shown here:
void keyPressed(KeyEvent ke )
void keyReleased(KeyEvent ke )
void keyTyped(KeyEvent ke )
The MouseListener Interface
This interface defines five methods. If the mouse is pressed and released at the same point,
mouseClicked( ) is invoked. When the mouse enters a component, the mouseEntered( ) method
is called. When it leaves, mouseExited( ) is called. The mousePressed( ) and mouseReleased( )
methods are invoked when the mouse is pressed and released, respectively.
The general forms of these methods are shown here:
void mouseClicked(MouseEvent me )
void mouseEntered(MouseEvent me )
void mouseExited(MouseEvent me )
void mousePressed(MouseEvent me )
void mouseReleased(MouseEvent me )

The MouseMotionListener Interface


This interface defines two methods. The mouseDragged( ) method is called multiple times as the
mouse is dragged. The mouseMoved( ) method is called multiple times as the mouse is moved.

Their general forms are shown here:


void mouseDragged(MouseEvent me )
void mouseMoved(MouseEvent me )
The TextListener Interface
This interface defines the textChanged( ) method that is invoked when a change occurs in a text
area or text field.
Its general form is shown here: void textChanged(TextEvent te )

Handling Mouse Events


To handle mouse events, we must implement the MouseListener and the MouseMotion Listener
interfaces.
EX: // Demonstrate the mouse event handlers.
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/
public class MouseEvents extends Applet implements MouseListener, MouseMotionListener
{ String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init() {
addMouseListener(this);
addMouseMotionListener(this);
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me)
{ mouseX = 0; // save coordinates
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
// Handle mouse entered.
public void mouseEntered(MouseEvent me) {
// save
coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}

// Handle mouse exited.


public void mouseExited(MouseEvent me) {
// save
coordinate
s mouseX
= 0;
9
=673587[+/

mouseY =
10;
msg = "Mouse exited.";
repaint();
}
// Handle button pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
mouseX =
[Link]();
mouseY =
[Link](); msg =
"Down"; repaint();
}
// Handle button released.
public void mouseReleased(MouseEvent me) {
1. save
coordinates
mouseX
=[Link]();
mouseY =
*/7+[Link](
);
msg
= "Up";
repaint();
}
2. Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
1. save coordinates
mouseX =
[Link]();

mouseY = [Link](); msg = "*";


showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
// Handle mouse moved.
public void mouseMoved(MouseEvent me) {
// show status
showStatus("Moving mouse at " + [Link]() + ", " + [Link]());
}
// Display msg in applet window at current X,Y location.
public void paint(Graphics g) {
[Link](msg, mouseX, mouseY);
}
}
Handling Keyboard Events
When a key is pressed, a KEY_PRESSED event is generated. This results in a call to the
keyPressed( ) event handler. When the key is released, a KEY_RELEASED event is generated
and the keyReleased( ) handler is executed. If a character is generated by the keystroke, then a
KEY_TYPED event is sent and the keyTyped( ) handler is invoked.
Thus, each time the user presses a key, at least two and often three events are generated. If all
you care about are actual characters, then you can ignore the information passed by the key press
and release events.
EX: // Demonstrate the key event handlers.
import [Link].*;
import [Link].*;
import [Link].*;
/* <applet code="SimpleKey" width=300
height=100> </applet> */
public class SimpleKey extends Applet implements KeyListener
{
String msg = "";
int X = 10, Y = 20; // output coordinates
public void init() {
addKeyListener(this);
requestFocus(); // request input focus
}
public void keyPressed(KeyEvent ke)
{ showStatus("Key Down"); }

public void keyReleased(KeyEvent ke)


{ showStatus("Key Up");
}

public void keyTyped(KeyEvent ke)


{ msg += [Link]();
repaint();
}
// Display keystrokes.
public void paint(Graphics g)
{ [Link](msg, X, Y); }

}
Adapter Classes
Java provides a special feature, called an adapter class , that can simplify the creation of event
handlers in certain situations. An adapter class provides an empty implementation of all methods
in an event listener interface.
Adapter classes are useful when you want to receive and process only some of the events that are
handled by a particular event listener interface.
For example, the MouseMotionAdapter class has two methods, mouseDragged( ) and
mouseMoved( ) . The signatures of these empty methods are exactly as defined in the
MouseMotionListener interface. If you were interested in only mouse drag events, then you
could simply extend MouseMotionAdapter and implement mouseDragged( ) . The empty
implementation of mouseMoved( ) would handle the mouse motion events for you.
Adapter Class
ComponentAdapter Listener Interface
ContainerAdapter ComponentListener
FocusAdapter ContainerListener
KeyAdapter FocusListener
MouseAdapter KeyListener
MouseMotionAdapter MouseListener
WindowAdapter MouseMotionListener
WindowListener
EX: // Demonstrate an adapter.
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="AdapterDemo" width=300 height=100>
</applet>
*/
public class AdapterDemo extends Applet
{
public void init() {
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new
MyMouseMotionAdapter(this)); }
}
class MyMouseAdapter extends MouseAdapter
{
AdapterDemo adapterDemo;
public MyMouseAdapter(AdapterDemo adapterDemo)
{
[Link] = adapterDemo;
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me)
{ [Link]("Mouse clicked");
}
}

class MyMouseMotionAdapter
extends MouseMotionAdapter {
AdapterDemo adapterDemo;
public MyMouseMotionAdapter(AdapterDemo adapterDemo)
{
[Link] = adapterDemo;
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me)
{
[Link]("Mouse dragged");
}
}

Files and Streams:


Text stream classes for reading data Text stream classes for writing data
Stream
A stream can be defined as a sequence of data. There are two kinds of Streams −
 InPutStream − The InputStream is used to read data from a source.
 OutPutStream − The OutputStream is used for writing data to a destination.

Java provides strong but flexible support for I/O related to files and networks.
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes are, FileInputStream and
FileOutputStream.
Example
import [Link].*;
public class CopyFile
{
public static void main(String args[]) throws IOException
{ FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("[Link]");
out = new FileOutputStream("[Link]");
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
}finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
} } }}
Now let's have a file [Link] with the following content:
This is test for copy file.
$javac [Link]
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas
Java Character streams are used to perform input and output for 16-bit unicode. Though
there are many classes related to character streams but the most frequently used classes
are, FileReader and FileWriter.
Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but
here the major difference is that FileReader reads two bytes at a time and FileWriter writes two
bytes at a time.
Example
import [Link].*;
public class CopyFile
{
public static void main(String args[]) throws IOException
{ FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("[Link]");
out = new FileWriter("[Link]");
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
}finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
}
}
}
}

Reading and Writing Files Text input/output,


As described earlier, a stream can be defined as a sequence of data. The InputStream is used to
read data from a source and the OutputStream is used for writing data to a destination. Here is
a hierarchy of classes to deal with Input and Output streams.
-

The two important streams are FileInputStream and FileOutputStream (File Handling)
In Java, FileInputStream and FileOutputStream classes are used to read and write data in file. In
another words, they are used for file handling in java.
Java FileOutputStream class
Java FileOutputStream is an output stream for writing data to a file. It is a class belongs to byte
streams. It can be used to create text files.

First we should read data from the keyword. It uses DataInputStream class for reading data from the
keyboard is as:
DataInputStream dis=new DataInputStream([Link]);

FileOutputStream used to send data to the file and attaching the file to FileOutputStream. i.e.,
FileOutputStream fout=new FileOutputStream(“File_name”);

The next step is to read data from DataInputStream and write it into FileOutputStream. It means read data
from dis object and write it into fout object. i.e.,
ch=(char)[Link](); //read one character into ch
[Link](ch); //write ch into file.

Finally closing the file using: [Link]();
Creating a Text file:

Example: Write a program to read data from the keyboard and write it to [Link] file.
import [Link].*;
class Test{
public static void main(String args[])
{
DataInputStream dis=new DataInputStream([Link]);
FileOutputstream fout=new
FileOutputStream("[Link]"); [Link]("Enter
text @ at the end:”); char ch; while((ch=(char)[Link]())!
=‟@‟)
[Link](ch);
[Link]();
}
}
Output: javac [Link]
Java Test
Java FileInputStream class
It is useful to read data from a file in the form of sequence of bytes. It is possible to read data
from a text file using FileInputStream. i.e.,
FileInputStream fin= new FileInputStream(“[Link]”);

To read data from
the file is, ch=[Link]();
When there is no more data available to read then it returns -1.

The Output Stream is used to send data to the monitor. i.e., PrintStream, for displaying the data we can
use [Link].
[Link](ch);
Reading data from a text file using FileInputStream:

Java FileInputStream class obtains input bytes from a file. It is used for reading streams of raw
bytes such as image data. It should be used to read byte-oriented data for example to read image,
audio, video etc.

Example: Write a program to read data from [Link] using FileInputStream and display
it on monitor.
import [Link].*;
class ReadFile
{
public static void main(String args[])
{

FileInputStream fin=new
FileInputStream("[Link]"); [Link](“File
Contents:”); int ch; while((ch=[Link]())!=-1)
{
[Link]((char)ch);
}
[Link]();
}
}
Output: javac [Link]
java ReadFile
III

UNIT V: GUI Programming with Java – AWT class hierarchy, component, container,
panel, window, frame, graphics.
AWT controls: Labels, button, text field, check box, check box groups, choices, lists,
scrollbars, and graphics.
Layout Manager – Layout manager types: border, grid and flow.
Swing – Introduction, limitations of AWT, Swing vs AWT.

GUI PROGRAMMING WITH JAVA


ABSTRACT WINDOW TOOLKIT (AWT)
Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based application
in java. Java AWT components are platform-dependent i.e. components are displayed
according to the view of operating system. AWT is heavyweight i.e. its components uses the
resources of system. The Abstract Window Toolkit(AWT) support for applets. The AWT
contains numerous classes and methods that allow you to create and manage windows.
The [Link] package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
AWT Classes
The AWT classes are contained in the [Link] package. It is one of Java's largest packages.
Class Description
AWTEvent Encapsulates AWT events.
AWTEventMulticaster Dispatches events to multiple
listeners. BorderLayout Border layouts use five components:
North, South, East, West, and Center.
CardLayout Card layouts emulate index
cards. Only the one on top is
showing.
Checkbox Creates a check box control.
CheckboxGroup Creates a group of check box
controls. CheckboxMenuItem Creates an on/off menu item.
Choice Creates a pop-up list.
Color Manages colors in a portable, platform-independent fashion.
Component An abstract superclass for various AWT components.
Container A subclass of Component that can hold other components.
Cursor Encapsulates a bitmapped cursor.
Dialog Creates a dialog window.
Dimension Specifies the dimensions of an object. The width is stored in
width , and the height is stored in height .
Event Encapsulates events.
FlowLayout The flow layout manager. Flow layout positions components left
to right, top to bottom.
Frame Creates a standard window that has a title bar, resize corners,
and a menu bar.
Graphics Encapsulates the graphics context.
III

Control Fundamentals
The AWT supports the following types of controls:
3. Labels
4. Push buttons
5. Check boxes
6. Choice lists
7. Lists
8. Scroll bars
9. Text editing

User interaction with the program is of two types:


CUI (Character User Interface): In CUI user interacts with the application by
typing characters or commands. In CUI user should remember the commands. It is
not user friendly.
2. GUI (Graphical User Interface): In GUI user interacts with the application through graphics.
GUI is user friendly. GUI makes application attractive. It is possible to simulate real object in
GUI programs. In java to write GUI programs we can use awt (Abstract Window Toolkit)
package.

Java AWT Class Hierarchy


The hierarchy of Java AWT classes is given below.

Container
The Container is a component in AWT that can contain other components like buttons, textfields,
labels etc. The classes that extend Container class are known as container such as Frame, Dialog
and Panel.
III

Window
The window is the container that has no borders and menu bars. You must use frame, dialog or
another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
Useful Methods of Component class
Method Description
public void add(Component c) inserts a component on this component.
public void setSize(int width,int height) sets the size(width and height) of the component.
public void setLayout(LayoutManager m) defines the layout manager for the component.
public void setVisible(boolean status) changes the visibility of the component, by
default false.

Listeners and Listener Methods:


Listeners are available for components. A Listener is an interface that listens to an event from a
component. Listeners are available in [Link] package. The methods in the listener
interface are to be implemented, when using that listener.

Layout Managers
III

A layout manager arranges the child components of a container. It positions and sets the size of
components within the container's display area according to a particular layout scheme.
The layout manager's job is to fit the components into the available area, while maintaining the
proper spatial relationships between the components. AWT comes with a few standard layout
managers that will collectively handle most situations; you can make your own layout managers
if you have special requirements.
LayoutManager at work

Every container has a default layout manager; therefore, when you make a new container, it
comes with a LayoutManager object of the appropriate type. You can install a new layout
manager at any time with the setLayout() method. Below, we set the layout manager of a
container to a BorderLayout:
setLayout ( new BorderLayout( ) );
Every component determines three important pieces of information used by the layout manager
in placing and sizing it: a minimum size, a maximum size, and a preferred size.
These are reported by the getMinimumSize(), getMaximumSize(), and getPreferredSize(),
methods of Component, respectively.
When a layout manager is called to arrange its components, it is working within a fixed area. It
usually begins by looking at its container's dimensions, and the preferred or minimum sizes of
the child components.
Layout manager types
Flow Layout
FlowLayout is a simple layout manager that tries to arrange components with their preferred
sizes, from left to right and top to bottom in the display. A FlowLayout can have a specified
justification of LEFT, CENTER, or RIGHT, and a fixed horizontal and vertical padding.
By default, a flow layout uses CENTER justification, meaning that all components are centered
within the area allotted to them. FlowLayout is the default for Panel components like Applet.
III

The following applet adds five buttons to the default FlowLayout.


import [Link].*;
/*
<applet code="Flow" width="500" height="500">
</applet>
*/
public class Flow extends [Link]
{
public void init()
{
//Default for Applet is FlowLayout
add( new Button("One") );
add( new Button("Two") );
add( new Button("Three") );
add( new Button("Four") );
add( new Button("Five") );
}
}
If the applet is small enough, some of the buttons spill over to a second or third row.
Grid Layout
GridLayout arranges components into regularly spaced rows and columns. The components
are arbitrarily resized to fit in the resulting areas; their minimum and preferred sizes are
consequently ignored.
GridLayout is most useful for arranging very regular, identically sized objects and for
allocating space for Panels to hold other layouts in each region of the container.

GridLayout takes the number of rows and columns in its constructor. If you subsequently
give it too many objects to manage, it adds extra columns to make the objects fit. You can also
set the number of rows or columns to zero, which means that you don't care how many elements
the layout manager packs in that dimension.

For example, GridLayout(2,0) requests a layout with two rows and an unlimited number of
columns; if you put ten components into this layout, you'll get two rows of five columns each.
The following applet sets a GridLayout with three rows and two columns as its layout
manager;
import [Link].*;
/*
<applet code="Grid" width="500"
height="500"> </applet>
*/
public class Grid extends [Link]
{
public void init()
{
setLayout( new GridLayout( 3, 2 ));
III

add( new Button("One") );


add( new Button("Two") );
add( new Button("Three") );
add( new Button("Four") );
add( new Button("Five") );
}
}

The five buttons are laid out, in order, from left to right, top to bottom, with one empty spot.

Border Layout
BorderLayout is a little more interesting. It tries to arrange objects in one of five geographical
locations: "North," "South," "East," "West," and "Center," possibly with some padding between.
BorderLayout is the default layout for Window and Frame objects. Because each
component is associated with a direction, BorderLayout can manage at most five components; it
squashes or stretches those components to fit its constraints.
When we add a component to a border layout, we need to specify both the component and the
position at which to add it. To do so, we use an overloaded version of the add() method that
takes an additional argument as a constraint.
The following applet sets a BorderLayout layout and adds our five buttons again, named for
their locations;

import [Link].*;
/*
<applet code="Border" width="500" height="500">
</applet>
*/
public class Border extends [Link]
{
public void init()
{
setLayout( new [Link]() );
add( new Button("North"), "North" ); add(
new Button("East"), "East" );
add( new Button("South"), "South" );
add( new Button("West"), "West" );
add( new Button("Center"), "Center" );
}
}

Compile: javac [Link]


Run : appletviewer [Link]
III

Java AWT Example


To create simple awt example, you need a frame. There are two ways to create a frame in AWT.
// By extending Frame class (inheritance)
2. By creating the object of Frame class (association)

Simple example of AWT by inheritance


import [Link].*;
class First extends Frame{
First(){
Button b=new Button("click me");
[Link](30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300
height setLayout(null);//no layout manager
setVisible(true);//now frame will be visible }

public static void main(String args[])


{ First f=new First();
}
}
Simple example of AWT by association
import [Link].*;
class First2{
First2(){
Frame f=new Frame();
Button b=new Button("click
me"); [Link](30,50,80,30);
[Link](b);
[Link](300,300);
[Link](null);
[Link](true);
}
public static void main(String args[])
{ First2 f=new First2();
}
}
III

AWT controls
Labels:
The easiest control to use is a label. A label is an object of type Label, and it contains a string,
which it displays. Labels are passive controls that do not support any interaction with the user.
// Demonstrate
Labels import
[Link].*; import
[Link].*; /*
<applet code="LabelDemo" width=300 height=200>
</applet> */
public class LabelDemo extends Applet
{
public void init()
{
Label one = new Label("One");
Label two = new Label("Two");
Label three = new Label("Three");
add labels to applet window
add(one);
add(two);
add(three);
}
}
Buttons:
The most widely used control is the push button. A push button is a component that contains a
label and that generates an event when it is pressed. Push buttons are objects of type Button.
Button class is useful to create push buttons. A push button triggers a series of events.
To create push button: Button b1 =new Button("label");
To get the label of the button: String l = [Link]();
To set the label of the button: [Link]("label");
To get the label of the button clicked: String str = [Link]();

\{ Demonstrate Buttons
import [Link].*;
import [Link].*;
import [Link].*;
/* <applet code="ButtonDemo" width=250 height=150>
</applet> */

public class ButtonDemo extends Applet implements ActionListener


{
String msg = "";
Button yes, no, maybe;
III

public void init()


{
yes = new Button("Yes");
no = new Button("No");
maybe = new Button("Undecided");
add(yes);
add(no);
add(maybe);
[Link](this);
[Link](this);
[Link](this);
}

public void actionPerformed(ActionEvent ae)


{
String str = [Link]();
if([Link]("Yes"))
{
msg = "You pressed Yes.";
}
else if([Link]("No"))
{
msg = "You pressed No.";
}
else
{
msg = "You pressed Undecided.";
}
repaint();
}
public void paint(Graphics g)
{
[Link](msg, 6, 100);
}
}

Check Boxes:
A check box is a control that is used to turn an option on or off. It consists of a small box that
can either contain a check mark or not. There is a label associated with each check box that
describes what option the box represents. You change the state of a check box by clicking on
it. Check boxes can be used individually or as part of a group.

\{ Demonstrate check boxes.


import [Link].*;
import [Link].*;
import [Link].*;
III

/*
<applet code="CheckboxDemo" width=250 height=200>
</applet>
*/
public class CheckboxDemo extends Applet implements ItemListener
{
String msg = "";
checkbox Win98, winNT, solaris, mac;

public void init()


{
win98 = new Checkbox("Windows 98/XP", null,
true); winNT = new Checkbox("Windows NT/2000");
solaris = new Checkbox("Solaris"); mac = new
Checkbox("MacOS");
add(Win98);
add(winNT);
add(solaris);
add(mac);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
// Display current state of the check boxes.

public void paint(Graphics g)


{
msg = "Current state: ";
[Link](msg, 6, 80);
msg = " Windows 98/XP: " + [Link]();
[Link](msg, 6, 100);
msg = " Windows NT/2000: " + [Link]();
[Link](msg, 6, 120);
msg = " Solaris: " + [Link]();
[Link](msg, 6, 140);
msg = " MacOS: " + [Link]();
[Link](msg, 6, 160);
}
}
III

TextField:
The TextField class implements a single-line text-entry area, usually called an edit control.
Text fields allow the user to enter strings and to edit the text using the arrow keys, cut and
paste keys, and mouse selections.
// Demonstrate text field.
import [Link].*;
import
[Link].*;
import [Link].*;
/*
<applet code="TextFieldDemo" width=380 height=150>
</applet>
*/
public class TextFieldDemo extends Applet implements ActionListener
{
TextField name, pass;

public void init()


{
Label namep = new Label("Name: ", [Link]);
Label passp = new Label("Password: ", [Link]);
name = new TextField(12);
pass = new TextField(8);
[Link]('?');
add(namep);
add(name);
add(passp);
add(pass);
// register to receive action events
[Link](this);
[Link](this);
}
// User pressed Enter.
public void actionPerformed(ActionEvent ae)
{
repaint();
}
public void paint(Graphics g)
{
[Link]("Name: " + [Link](), 6, 60);
[Link]("Selected text in name: " + [Link](), 6, 80);
[Link]("Password: " + [Link](), 6, 100);
}
}
III

TextArea:
Sometimes a single line of text input is not enough for a given task. To handle these
situations, the AWT includes a simple multiline editor called TextArea .

\{ Demonstrate
TextArea. import
[Link].*; import
[Link].*;
/*
<applet code="TextAreaDemo" width=300
height=250> </applet>
*/
public class TextAreaDemo extends Applet
{
public void init()
{
String val = "There are two ways of constructing " + "a software design.\n" + "One way is to
make it so simple\n" + "that there are obviously no deficiencies.\n" + "And the other way is to
make it so complicated\n" + "that there are no obvious deficiencies.\n\n" + " -C.A.R. Hoare\n\n"
+ "There's an old story about the person who wished\n" + "his computer were as easy to use as
his telephone.\n" + "That wish has come true,\n" + "since I no longer know how to use my
telephone.\n\n" + " -Bjarne Stroustrup, AT&T, (inventor of C++)";
TextArea text = new TextArea(val, 10, 30);
add(text);
}
}

CheckboxGroup
It is possible to create a set of mutually exclusive check boxes in which one and only one
check box in the group can be checked at any one time. These check boxes are often called
radio buttons. A Radio button represents a round shaped button such that only one can be
selected from a panel. Radio button can be created using CheckboxGroup class and
Checkbox classes.
· To create a radio button: CheckboxGroup cbg = new CheckboxGroup ();
Checkbox cb = new Checkbox ("label", cbg, true);
· To know the selected checkbox: Checkbox cb = [Link] ();
· To know the selected checkbox label: String label = [Link]().getLabel ();

\{ Demonstrate check box group.


import [Link].*;
import [Link].*;
import [Link].*;

/*
<applet code="CBGroup" width=250 height=200>
</applet>
*/

public class CBGroup extends Applet implements ItemListener


{
String msg = "";
Checkbox Win98, winNT, solaris, mac;
CheckboxGroup cbg;
public void init() {
cbg = new CheckboxGroup();
Win98 = new Checkbox("Windows 98/XP", cbg, true);
winNT = new Checkbox("Windows NT/2000", cbg, false);
solaris = new Checkbox("Solaris", cbg, false); mac = new
Checkbox("MacOS", cbg, false);
add(Win98);
add(winNT);
add(solaris);
add(mac);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
}
public void itemStateChanged(ItemEvent ie) {
repaint();
}
\{ Display current state of the check
boxes. public void paint(Graphics g)
{
msg = "Current selection: ";
msg += [Link]().getLabel();
[Link](msg, 6, 100);
}
}
Choice Controls
The Choice class is used to create a pop-up list of items from which the user may choose.
Thus, a Choice control is a form of menu. Choice menu is a popdown list of items. Only
one item can be selected.
· To create a choice menu: Choice ch = new Choice();
· To add items to the choice menu: [Link] ("text");
· To know the name of the item selected from the choice menu:
String s = [Link] ();
· To know the index of the currently selected item: int i = [Link]();
This method returns -1, if nothing is selected.
//Demonstrate Choice
lists. import
[Link].*; import
[Link].*;
import [Link].*;
/*
<applet code="ChoiceDemo" width=300
height=180> </applet>
*/
public class ChoiceDemo extends Applet implements ItemListener
{ Choice os, browser;
String msg = ""; public
void init() { os = new
Choice(); browser = new
Choice();
//add items to os list
[Link]("Windows 98/XP");
[Link]("Windows NT/2000");
[Link]("Solaris");
[Link]("MacOS");
\{ add items to browser list
[Link]("Netscape 3.x");
[Link]("Netscape 4.x");
[Link]("Netscape 5.x");
[Link]("Netscape 6.x");
[Link]("Internet Explorer
4.0"); [Link]("Internet
Explorer 5.0");
[Link]("Internet Explorer
6.0"); [Link]("Lynx 2.4");
[Link]("Netscape 4.x");
\{ add choice lists to
window add(os);
add(browser);
\{ register to receive item
events
[Link](this);
[Link](
this);
}
-V
public void itemStateChanged(ItemEvent ie) {
repaint();
}
// Display current selections.
public void paint(Graphics g)
{ msg = "Current OS: ";
msg += [Link]();
[Link](msg, 6, 120);
msg = "Current Browser: ";
msg += [Link]();
[Link](msg, 6, 140);
}
}

Lists
The List class provides a compact, multiple-choice, scrolling selection list. Unlike the
Choice object, which shows only the single selected item in the menu, a List object can be
constructed to show any number of choices in the visible window. It can also be created to
allow multiple selections. List provides these constructors: List( )
List(int numRows )
List(int numRows , boolean multipleSelect )
A List box is similar to a choice box, it allows the user to select multiple items.
· To create a list box:
(or) List lst = new List();

List lst = new List (3, true);


This list box initially displays 3 items. The next parameter true represents that the user can
select more than one item from the available items. If it is false, then the user can select only
one item.
= To add items to the list box: [Link]("text");
= To get the selected items: String x[] = [Link]();
= To get the selected indexes: int x[] = [Link] ();
// Demonstrate Lists.
import [Link].*; import
[Link].*; import
[Link].*; /*
<applet code="ListDemo" width=300 height=180>
</applet>
*/
public class ListDemo extends Applet implements ActionListener
{ List os, browser;
String msg = "";
public void init() { os
= new List(4, true);
UNIT -V
browser = new List(4, false);
\} add items to os list
[Link]("Windows 98/XP");
[Link]("Windows
NT/2000");
[Link]("Solaris");
[Link]("MacOS");
\} add items to browser list
[Link]("Netscape 3.x");
[Link]("Netscape 4.x");
[Link]("Netscape 5.x");
[Link]("Netscape 6.x");
[Link]("Internet Explorer
4.0"); [Link]("Internet
Explorer 5.0");
[Link]("Internet Explorer
6.0"); [Link]("Lynx 2.4");
[Link](1);
\} add lists to window
add(os);
add(browser);
// register to receive action
events
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent ae)
{ repaint();
}
// Display current selections.
public void paint(Graphics
g)
{
int idx[];
msg = "Current OS: ";
idx = [Link]();
for(int i=0; i<[Link]; i++)
msg += [Link](idx[i]) + " ";
[Link](msg, 6, 120);
msg = "Current Browser: ";
msg += [Link]();
[Link](msg, 6, 140);
}
}
Scroll Bars
Scroll bars are used to select continuous values between a specified minimum and maximum.
Scroll bars may be oriented horizontally or vertically. Scrollbar class is useful to create
scrollbars that can be attached to a frame or text area. Scrollbars can be arranged vertically or
horizontally.
UNIT -V
\{ To create a scrollbar : Scrollbar sb = new Scrollbar (alignment, start, step, min,
max); alignment: [Link], [Link]
start: starting value (e.g. 0)
step: step value (e.g. 30) // represents scrollbar length
min: minimum value (e.g. 0)
max: maximum value (e.g. 300)
· To know the location of a scrollbar: int n = [Link] ();
· To update scrollbar position to a new position: [Link] (int position);
· To get the maximum value of the scrollbar: int x = [Link] ();
· To get the minimum value of the scrollbar: int x = [Link] ();
· To get the alignment of the scrollbar: int x = getOrientation ();
This method return 0 if the scrollbar is aligned HORIZONTAL, 1 if aligned VERTICAL.
// Demonstrate scroll bars.
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="SBDemo" width=300 height=200>
</applet>
*/
public class SBDemo extends Applet
implements AdjustmentListener, MouseMotionListener
{ String msg = "";
Scrollbar vertSB, horzSB;
public void init() {
int width = [Link](getParameter("width")); int
height = [Link](getParameter("height"));
vertSB = new Scrollbar([Link], 0, 1, 0, height);
horzSB = new Scrollbar([Link], 0, 1, 0, width);
add(vertSB);
add(horzSB);
// register to receive adjustment events
[Link](this);
[Link](this);
addMouseMotionListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent ae) {
repaint();
}
// Update scroll bars to reflect mouse dragging.
public void mouseDragged(MouseEvent me) {
int x = [Link]();
int y = [Link]();
[Link](y);
[Link](x);
UNIT -V
repaint();
}
// Necessary for MouseMotionListener
public void mouseMoved(MouseEvent me)
{
}
// Display current value of scroll
bars. public void paint(Graphics g) {
msg = "Vertical: " + [Link]();
msg += ", Horizontal: " +
[Link](); [Link](msg, 6,
160);
\} show current mouse drag position
[Link]("*", [Link](),
[Link]());
}
}
Graphics
The AWT supports a rich assortment of graphics methods. All graphics are drawn relative to
a window.
Graphics class and is obtained in two ways:
\} It is passed to an applet when one of its various methods, such as paint( ) or update(),
is called.
\} It is returned by the getGraphics( ) method of Component.
Drawing Lines
Lines are drawn by means of the drawLine( ) method, shown here:
void drawLine(int startX, int startY, int endX, int endY)
drawLine( ) displays a line in the current drawing color that begins at startX,startY and ends
at endX,endY.
The following applet draws several lines:
// Draw lines
import [Link].*;
import
[Link].*; /*

<applet code="Lines" width=300


height=200> </applet>
*/
public class Lines extends Applet
{ public void paint(Graphics g)
{ [Link](0, 0, 100, 100);
[Link](0, 100, 100, 0);
[Link](40, 25, 250, 180);
[Link](75, 90, 400, 400);
[Link](20, 150, 400, 40);
[Link](5, 290, 80, 19);
}}
UNIT -V
Drawing Rectangles
The drawRect( ) and fillRect( ) methods display an outlined and filled rectangle, respectively.
They are shown here:
void drawRect(int top, int left, int width, int height)
void fillRect(int top, int left, int width, int height)
The upper-left corner of the rectangle is at top,left. The dimensions of the rectangle
are specified by width and height.
To draw a rounded rectangle, use drawRoundRect( ) or fillRoundRect( ), both shown
here: void drawRoundRect(int top, int left, int width, int height,int xDiam, int
yDiam) void fillRoundRect(int top, int left, int width, int height, int xDiam, int
yDiam)
// Draw rectangles
import [Link].*;
import [Link].*;
/*
<applet code="Rectangles" width=300
height=200> </applet>
*/
public class Rectangles extends Applet
{ public void paint(Graphics g)
{ [Link](10, 10, 60, 50); [Link](100,
10, 60, 50); [Link](190, 10,
60, 50, 15, 15); [Link](70, 90,
140, 100, 30, 40);
}
}
Drawing Ellipses and Circles
To draw an ellipse, use drawOval( ). To fill an ellipse, use fillOval( ). These methods
are shown here:
void drawOval(int top, int left, int width, int height)
void fillOval(int top, int left, int width, int height)
// Draw
Ellipses
import
[Link].*
; import
[Link]
t.*; /*
<applet code="Ellipses" width=300
height=200> </applet>
*/
public class Ellipses extends Applet
{ public void paint(Graphics g)
{ [Link](10, 10, 50, 50);
[Link](100, 10, 75, 50);
[Link](190, 10, 90, 30);
[Link](70, 90, 140, 100);
}}
Drawing Arcs
Arcs can be drawn with drawArc( ) and fillArc( ), shown here:
void drawArc(int top, int left, int width, int height, int startAngle,int sweepAngle)
void fillArc(int top, int left, int width, int height, int startAngle,int sweepAngle)
The arc is bounded by the rectangle whose upper-left corner is specified by top,left and whose
width and height are specified by width and height. The arc is drawn from startAngle through
the angular distance specified by sweepAngle. Angles are specified in degrees.
Zero degrees is on the horizontal, at the three o’clock position. The arc is drawn
counterclockwise if sweepAngle is positive, and clockwise if sweepAngle is negative.
Therefore, to draw an arc from twelve o’clock to six o’clock, the start angle would be 90 and
the sweep angle 180.
Drawing Polygons
It is possible to draw arbitrarily shaped figures using drawPolygon( ) and fillPolygon(
), shown here:
void drawPolygon(int x[ ], int y[ ], int numPoints)
void fillPolygon(int x[ ], int y[ ], int numPoints)
The polygon’s endpoints are specified by the coordinate pairs contained within the x and y
arrays. The number of points defined by x and y is specified by numPoints. There are
alternative forms of these methods in which the polygon is specified by a Polygon object.
The following applet draws several arcs:
The following applet draws an
//Draw Arcs
hourglass shape:
import
[Link].*;
// Draw Polygon
import
import
[Link].*;
[Link].*;
/*
import
[Link].*;
<applet code="Arcs"
/*
width=300 height=200>
<applet code="HourGlass"
</applet>
width=230 height=210>
*/
</applet>
public class Arcs extends Applet
*/
{ public void paint(Graphics g)
public class HourGlass extends Applet
{ [Link](10, 40, 70, 70, 0, 75);
{ public void paint(Graphics g) {
[Link](100, 40, 70, 70, 0, 75);
int xpoints[] = {30, 200, 30, 200, 30};
[Link](10, 100, 70, 80, 0, 175);
int ypoints[] = {30, 30, 200, 200, 30};
[Link](100, 100, 70, 90, 0, 270);
int num = 5; [Link](xpoints,
[Link](200, 80, 80, 80, 0, 180);
ypoints, num);
} }
}
SWINGS
Swing is a set of classes that provides more powerful and flexible components than are
possible with the AWT. Swing is a GUI widget toolkit for Java. It is part of Oracle's Java
Foundation Classes (JFC) that is used to create window-based applications. It is built on
the top of AWT (Abstract Windowing Toolkit) API and entirely written in java.

In addition to the familiar components, such as buttons, check boxes, and labels, Swing
supplies several exciting additions, including tabbed panes, scroll panes, trees, and tables.
Even familiar components such as buttons have more capabilities in Swing. For example, a
button may have both an image and a text string associated with it. Also, the image can be
changed as the state of the button changes.

Unlike AWT components, Swing components are not implemented by platform specific
code. Instead, they are written entirely in Java and, therefore, are platform-independent.
The term lightweight is used to describe such elements.

The [Link] package provides classes for java swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Differences between AWT and Swing

AWT Swing

AWT components are called Heavyweight Swings are called light weight component
component. because swing components sits on the top of
AWT components and do the work.

AWT components are platform dependent. Swing components are made in purely java and
they are platform independent.

AWT components require [Link] package. Swing components require [Link]


package.

AWT is a thin layer of code on top of the OS. Swing is much larger. Swing also has very
much richer functionality.

AWT stands for Abstract windows toolkit. Swing is also called as JFC’s (Java Foundation
classes).

This feature is not supported in AWT. We can have different look and feel in Swing.

Using AWT, you have to implement a lot of Swing has them built in.
things yourself.
This feature is not available in AWT. Swing has many advanced features like JTabel, Jtabbed pane w

The Swing component classes are:


Class Description
AbstractButton Abstract superclass for Swing buttons.
ButtonGroup Encapsulates a mutually exclusive set ofbuttons.
ImageIcon Encapsulates an icon.
JApplet The Swing version of Applet.
JButton The Swing push buttonclass.
JCheckBox The Swing check box class.
JComboBox Encapsulates a combo box (combination of a drop-down list & text
field). JLabel The Swing version of a label.
JRadioButton The Swing version of a radio button.
JScrollPane Encapsulates a scrollablewindow.
JTabbedPane Encapsulates a tabbed window.
JTable Encapsulates a table-based control.
JTextField The Swing version of a text field.
JTree Encapsulates a tree-based control.
Hierarchy for Swing components:
JApplet
Fundamental to Swing is the JApplet class, which extends Applet. Applets that use Swing must
be subclasses of JApplet. JApplet is rich with functionality that is not foundin Applet.
The content pane can be obtained via the method shown here:
Container getContentPane( )
The add( ) method of Container can be used to add a component to a content pane. Its form is
shown here:
void add(comp)
Here, comp is the component to be added to the content pane.
JFrame
Create an object to JFrame: JFrame ob = new JFrame ("title"); (or)
Create a class as subclass to JFrame class: MyFrame extends JFrame
Create an object to that class : MyFrame ob = new MyFrame ();
Example: Write a program to create a frame by creating an object to
JFrame class. //A swing Frame
import [Link].*;
class MyFrame
{
public static void main (String agrs[])
{ JFrame jf = new JFrame ("My Swing Frame...");
[Link] (400,200);
[Link] (true);
[Link] (JFrame.EXIT_ON_CLOSE);
}
}

Note: To close the frame, we can take the help of getDefaultCloseOperation () method of
JFrame class, as shown here: getDefaultCloseOperation (constant);
where the constant can be any one of the following:
◼ JFrame.EXIT_ON_CLOSE: This closes the application upon clicking on close button.
◼ JFrame.DISPOSE_ON_CLOSE: This disposes the present frame which is visible
on the screen. The JVM may also terminate.
◼ JFrame.DO_NOTHING_ON_CLOSE: This will not perform any operation
uponclicking on close button.
◼ JFrame.HIDE_ON_CLOSE: This hides the frame upon clicking on close button.

Window Panes: In swings the components are attached to the window panes only. A window
pane represents a free area of a window where some text or components can be displayed. For
example, we can create a frame using JFrame class in [Link] which contains a free area
inside it, this free area is called 'window pane'. Four types of window panes are available in
[Link] package.
Glass Pane: This is the first pane and is very close to the monitors screen. Any components to
be displayed in the foreground are attached to this glass pane. To reach this glass pane, we use
getGlassPane () method of JFrame class.
Root Pane: This pane is below the glass pane. Any components to be displayed in the
background are displayed in this pane. Root pane and glass pane are used in animations also.
For example, suppose we want to display a flying aeroplane in the sky. The aeroplane can be
displayed as a .gif or .jpg file in the glass pane where as the blue sky can be displayed in the root
pane in the background. To reach this root pane, we use getRootPane () method of JFrame class.
Layered Pane: This pane lies below the root pane. When we want to take several components
as a group, we attach them in the layered pane. We can reach this pane by calling
getLayeredPane () method of JFrame class.
Content Pane: This is the bottom most pane of all. Individual components are attached to this
pane. To reach this pane, we can call getContentPane () method of JFrame class.
Displaying Text in the Frame:
paintComponent (Graphics g) method of JPanel class is used to paint the portion of a component
in swing. We should override this method in our class. In the following example, we are writing
our class MyPanel as a subclass to JPanel and override the painComponent () method.

Write a program to display text in the frame


import [Link].*;
import [Link].*;
class MyPanel extends JPanel
{ public void paintComponent (Graphics g)
{ [Link] (g); //call JPanel’s method
setBackground ([Link]);
g.s etColor ([Link]);
etFont (new Font("Courier New",[Link],30));
rawString ("Hello Readers!", 50, 100);
}
}
class FrameDemo extends JFrame
{ FrameDemo ()
{
Container c = getContentPane ();
MyPanel mp = new MyPanel ();
[Link] (mp);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{ FrameDemo ob = new FrameDemo ();
[Link] (600, 200);
[Link] (true);
}
}

TEXT FIELDS
The Swing text field is encapsulated by the JTextComponent class, which extends JComponent.
It provides functionality that is common to Swing text components. One of its subclasses is
JTextField, which allows you to edit one line of text. Some of its constructors are shown here:
JTextField( )
JTextField(int cols)
JTextField(String s, int cols)
JTextField(String s)
import [Link].*;
import [Link].*;
/*
<applet code="JTextFieldDemo" width=300 height=50>
</applet>
*/
public class JTextFieldDemo extends JApplet
{ JTextField jtf;
public void init()
{
// Get content pane
Container contentPane = getContentPane();
[Link](new FlowLayout());
// Add text field to content
pane jtf = new
JTextField(15);
[Link](jtf);
}
}

BUTTONS
Swing buttons provide features that are not found in the Button class defined by the AWT. For
example, you can associate an icon with a Swing button. Swing buttons are subclasses of the
AbstractButton class, which extends JComponent. AbstractButton contains many methods that
allow you to control the behavior of buttons, check boxes, and radio buttons.
The JButton Class
The JButton class provides the functionality ofa push button. JButton allows an icon, a string, or
both to be associated with the push button. Some of its constructors are shown here:
· To create a JButton with text: JButton b = new JButton (“OK”);
· To create a JButton with image: JButton b = new JButton (ImageIcon ii);
· To create a JButton with text & image: JButton b = new JButton (“OK”, ImageIcon ii);
It is possible to create components in swing with images on it. The image is specified by
ImageIcon class object.
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="JButtonDemo" width=250 height=300>
</applet>
*/
public class JButtonDemo extends JApplet implements ActionListener
{ JTextField jtf;
public void init() {
// Get content pane
Container contentPane = getContentPane();
[Link](new FlowLayout());
// Add buttons to content pane
ImageIcon france = new ImageIcon("[Link]");
JButton jb = new JButton(france);
[Link]("France");
[Link](this); [Link](jb);

ImageIcon germany = new ImageIcon("[Link]");


jb = new JButton(germany);
[Link]("Germany");
[Link](this);
[Link](jb);
ImageIcon italy = new
ImageIcon("[Link]"); jb = new
JButton(italy);
[Link]("Italy");
[Link](this);
[Link](jb);
ImageIcon japan =
newImageIcon("[Link]"); jb = new
JButton(japan);
[Link]("Japan");
[Link](this);
[Link](jb);
// Add text field to
content pane jtf =
new JTextField(15);
[Link](jtf);
}
public void actionPerformed(ActionEvent ae)
{ [Link]([Link]());
}
}
CHECK BOXES
The JCheckBox class, which provides the functionality of a check box, is a concrete
implementation of AbstractButton. Its immediate superclass is JToggleButton, which provides
support for two-state buttons. Some of its constructors are shown here:
JCheckBox(Icon i)
JCheckBox(Icon i, boolean state)
JCheckBox(String s)
JCheckBox(String s, boolean state)
JCheckBox(String s, Icon i)
JCheckBox(String s, Icon i, boolean state)
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="JCheckBoxDemo" width=400 height=50>
</applet>
*/
public class JCheckBoxDemo extends JApplet implements ItemListener
{ JTextField jtf;
public void init()
{
// Get content pane
Container contentPane = getContentPane();
[Link](new FlowLayout());
// Create icons
ImageIcon normal = new ImageIcon("[Link]");
ImageIcon rollover = new ImageIcon("[Link]");
ImageIcon selected = new ImageIcon("[Link]");
// Add check boxes to the content pane
JCheckBox cb = new JCheckBox("C", normal);
[Link](rollover);
[Link](selected);
[Link](this); [Link](cb);

cb = new JCheckBox("C++",
normal);[Link](rollover);
[Link](selected);
[Link](this);
[Link](cb);
cb = new JCheckBox("Java",normal);
[Link](rollover);
[Link](selected);
[Link](this);
[Link](cb);
cb = new JCheckBox("Perl",normal);
[Link](rollover);
[Link](selected);
[Link](this);
[Link](cb);
// Add text field to the content pane
jtf = new JTextField(15);
[Link](jtf);
}
public void itemStateChanged(ItemEvent ie)
{ JCheckBox cb = (JCheckBox)[Link]();
[Link]([Link]());
}
}

RADIO BUTTONS
Radio buttons are supported by the JRadioButton class, which is a concrete implementation of
AbstractButton. Its immediate superclass is JToggleButton, which provides support for two-
state buttons. Some of its constructors are shown here:
JRadioButton(Icon i)
JRadioButton(Icon i, boolean state)
JRadioButton(String s)
JRadioButton(String s, boolean state)
JRadioButton(String s, Icon i)
JRadioButton(String s, Icon i, boolean state)
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="JRadioButtonDemo" width=300 height=50>
</applet>
*/
public class JRadioButtonDemo extends JApplet implements ActionListener
{ JTextField tf;
public void init() {
// Get content pane
Container contentPane = getContentPane();
[Link](new FlowLayout());
1. Add radio buttons to content pane
JRadioButton b1 = new
JRadioButton("A");
[Link](this);
[Link](b1);
JRadioButton b2 = new JRadioButton("B");
[Link](this);
[Link](b2);
JRadioButton b3 = new JRadioButton("C");
[Link](this);
[Link](b3);
[Link] a button group
ButtonGroup bg = new ButtonGroup();
[Link](b1);
[Link](b2);
[Link](b3);
// Create a text field and add it
// to the content pane
tf = new JTextField(5);
[Link](tf);
}
public void actionPerformed(ActionEvent ae) {
[Link]([Link]());
}
}
Limitations of AWT:
The AWT defines a basic set of controls, windows, and dialog boxes that support a usable, but limited graphical
interface. One reason for the limited nature of the AWT is that it translates its various visual components into
their corresponding, platform-specific equivalents or peers. This means that the look and feel of a component is
defined by the platform, not by java. Because the AWT components use native code resources, they are referred
to as heavy weight.
The use of native peers led to several problems.
First, because of variations between operating systems, a component might look, or even act, differently on
different platforms. This variability threatened java’s philosophy: write once, run anywhere.
Second, the look and feel of each component was fixed and could not be changed. Third, the use of heavyweight
components caused some frustrating restrictions. Due to these limitations Swing came and was integrated to java.
Swing is built on the AWT. Two key Swing features are: Swing components are light weight, Swing supports a
pluggable look and feel.

[Link] to demonstrate multithreading.


. Program to demonstrate JDBC concept using create a GUI based application for student information.
Program to display “Hello World” in web browser using applet.
. Program to add user controls to applets.
Write a program to create an application using concept of swing.
Program to demonstrate student registration functionality using servlets with session management.
JAVA PROGRAMMING Page

You might also like