Java Programming U6

Download as pdf or txt
Download as pdf or txt
You are on page 1of 75

RAGHU EDUCATIONAL INSTITUTIONS

Unit-VI
Applets and AWT

Java Programming RAGHU EDUCATIONAL INSTITUTIONS 1


Applets
• An applet is a special kind of java program that is designed
to be transmitted over the internet and automatically executed
by a java compatible web browser.

• Applet class is available in java.applet.* package. This class


provides all necessary support for applet creation, execution.
Some of the important methods which are almost used in all
applets are listed below:
• init()
• start()
• stop()
• destroy()
Java Programming RAGHU EDUCATIONAL INSTITUTIONS 2
Applets
Applets must also import java.awt.*, because all
applets run in a window. Then we need to get the support
from awt for the window activities. Applets are not executed
by the console-based java run-time interpreter. They are
executed by either a web browser or an applet viewer.

Properties of Applets:
• Applet programs doesn’t contain main() method
• An applet cannot run any executable program in the client
system
• An applet cannot communicate with any other server other
than the server from which it was downloaded
Java Programming RAGHU EDUCATIONAL INSTITUTIONS 3
Applets
Properties of Applets:
• An applet program cannot read a file or write into a file that
belongs to the client computer
• All life cycle methods need not require for every applet
program
• Applet programs are executed in a web browser or in
AppletViewer

Web pages can contain two types of applets which are named
after the location at which they are stored.
1. Local Applet
2. Remote Applet
Java Programming RAGHU EDUCATIONAL INSTITUTIONS 4
Applets
Local Applet:
A local applet is the one that is stored on our own
computer system. When the Web-page has to find a local
applet, it doesn't need to retrieve information from the
Internet.
A local applet is specified by a path name and a file
name as shown below in which the codebase attribute
specifies a path name, whereas the code attribute specifies the
name of the byte-code file that contains the applet's code.

<applet codebase="MyAppPath" code="MyApp.class"


width=200 height=200> </applet>
Java Programming RAGHU EDUCATIONAL INSTITUTIONS 5
Applets
Remote Applet:
A remote applet is the one that is located on a remote computer
system. This computer system may be located in the building next door
or it may be on the other side of the world. No matter where the remote
applet is located, it's downloaded onto our computer via the Internet.
The browser must be connected to the Internet at the time it needs to
display the remote applet.
To reference a remote applet in Web page, we must know the
applet's URL (where it's located on the Web) and any attributes and
parameters that we need to supply. A remote applet is specified by a url
and a file name as shown below.

<applet codebase="http://www.raghuenggcollege.com"
code="MyApp.class" width=200 height=200> </applet>
Java Programming RAGHU EDUCATIONAL INSTITUTIONS 6
Applet life cycle

Java Programming RAGHU EDUCATIONAL INSTITUTIONS 7


Applet life cycle
Born state: When an applet is loaded into the browser,
immediately browser invokes a method called init() to create
the applet in the local client system. The form of init()
method is:
public void init(){ … statements … }

Running state: When the user visited the page in which the
applet loaded, immediately applet starts it’s running by
invoking a method called start() method. This method is
invoked every time user revisits the applet page. The form of
start() method is:
public void start(){ … statements … }
Java Programming RAGHU EDUCATIONAL INSTITUTIONS 8
Applet life cycle
Stopped state: When the user minimizes the page in
which applet is running then applet is in stopped (paused)
state by invoking a method called stop() method. This method
is invoked every time the user minimizes the applet page. The
form of stop() method is:
public void stop(){ …statements …}

Dead state: When the applet page is closed then it is


terminated from the memory. This state is called Dead state.
This state can be visited only once in the life time of the
applet by invoking a method called destroy(). The form of
this method is:
public void destroy() { … statements … }
Java Programming RAGHU EDUCATIONAL INSTITUTIONS 9
Applet Structure
Almost every applet program overrides a set of
methods that provide the basic mechanism. We need to
override the four methods init(), start(), stop(), destroy() of
Applet class and another, paint() method of AWT class.
Applet Structure

paint(): Invoked immediately after the start() method, and


also any time the applet needs to repaint itself in the browser.
The method paint() gives us an access to an object
of Graphics class type in our applet code. Using the object of
Graphics class, we can call drawString() method of Graphics
class to write a text message in the applet window.

Java Programming RAGHU EDUCATIONAL INSTITUTIONS 10


Steps to create a simple applet program
Step1: Create an applet source program by extending Applet
class.

Step2: Compile the program.

Step3: Embed the applet program class file by using


<APPLET> tag in an HTML file.

Step4: Open the HTML file in a java enabled web browser.


The applet will be executed when the browser identifies the
APPLET tag within the HTML file. This HTML file
communicates with the server and loads the applet into the
client machine.
Java Programming RAGHU EDUCATIONAL INSTITUTIONS 11
Steps to create a simple applet program
<APPLET> tag: <APPLET> tag is useful to insert an applet
code into an HTML page. It has the following form,
<APPLET CODE=”name of the applet class file”
CODEBASE=”path of applet class file”
WIDTH= “width of applet window”
HEIGHT= “height of applet window”
ALIGN=alignment(LEFT/RIGHT/TOP/BOTTOM/CENTER)>
</APPLET>
<PARAM> tag: We can get any information from the
HTML file as a parameter. For this purpose, Applet class
provides a method named getParameter().
Syntax:
public String getParameter(String parameterName)
Java Programming RAGHU EDUCATIONAL INSTITUTIONS 12
sample Applet programs
Program to demonstrate creation of applet:
java code html code

Alternative way by combining both java and html code

Program to demonstrate <param> tag

Program to display background color

Applet life cycle program

Java Programming RAGHU EDUCATIONAL INSTITUTIONS 13


Graphics class
Graphics class is useful to draw something on the
window. By using this we can draw strings and also shapes
like rectangle, circle, oval, lines Etc. Some of the methods
offered by this class are listed below:

In all the following methods, x,y represent position, x


represents number of pixels away from left side and y
represents number of pixels away from the top.

public void drawString(String msg,int x, int y) – This is


used to display a string value on the window. Here msg
represents the text to be displayed.
Example: g.drawString(“Hai”,20,30);
Java Programming RAGHU EDUCATIONAL INSTITUTIONS 14
Graphics class
public void drawRect(int x,int y,int w,int h) – It will draw
a rectangle. Here, w is the width and h is the height.
Example: g.drawRect(10,10,30,20);

public void drawOval(int x,int y,int w,int h) – It will draw


oval shape within a bounding rectangle whose upper left
corner is (x,y) and w, h are the width and height.
Example: g.drawOval(20,20,25,20);
Example program 1 on Graphics class methods

public void setColor(Color colorname) – It will change the


foreground color. Here, Color is a class which offers
predefined colors
Java Programming RAGHU EDUCATIONAL INSTITUTIONS 15
Graphics class
public void fillRect(int x,int y,int w,int h) – It will create a
rectangle with specified dimensions then fill it with color
which is already set to the graphics.

public void fillOval(int x,int y,int w,int h) – It will create an


oval with specified dimensions then fill it with color which is
already set to the graphics.

Example program 2 on Graphics class methods

Java Programming RAGHU EDUCATIONAL INSTITUTIONS 16


Graphics class

Here are some pre defined colors of Color class:


Color.black Color.blue
Color.cyan Color.darkGray
Color.gray Color.green
Color.lightGray Color.orange
Color.pink Color.red
Color.magenta Color.white
Color.yellow

Java Programming RAGHU EDUCATIONAL INSTITUTIONS 17


Event Handling: event delegation model
In the delegation event model, a class designated as an
event source generates an event and sends it to one or more
listeners.

The responsibility of handling the event process is


handed over to its listeners. The listeners classes wait in the
vicinity, to spring into action only when its is poked by the
event that it is interested in.

However, the listeners must register or agree with the


event source class to receive any notification. This means that
a particular event is processed only by a specific listener.
Java Programming RAGHU EDUCATIONAL INSTITUTIONS 18
Event Handling: event delegation model

Java Programming RAGHU EDUCATIONAL INSTITUTIONS 19


Event Handling: event delegation model
The delegation event model can be defined by three
components: event, event source, and event listeners.

Events: The event object defines the change in state in the


event source class. For example, interacting with the
graphical interfaces, such as clicking a button or entering text
via keyboard in a text box, item selection in a list, all
represent some sort of change in the state.
The event object is used to carry the required
information about the state change. However, all events are
not caused by user interaction. There are events such as timer
event, hardware/software events, and so forth, that do not
depend upon user interaction.
Java Programming RAGHU EDUCATIONAL INSTITUTIONS 20
Event Handling: event delegation model
Event sources: Event sources are objects that cause the
events to occur due to some change in the property of the
component. Because there can be various types a component
can trigger, each must be registered to a listener to provide a
suitable response.

The general form of registration is given below,


source_reference.addTypeListener(TypeListener ref)

Event listeners: Event listeners are objects that are notified


as soon as a specific event occurs. Event listeners must define
the methods to process the notification they are interested to
receive.
Java Programming RAGHU EDUCATIONAL INSTITUTIONS 21
Event Handling: sources of event
Event classes are the classes that represent events of sources.
These are available in java.awt.event. * package. The
following are the event classes:

ActionEvent class:
An ActionEvent is generated when a button is pressed
or a list-item is double clicked or menu-item is selected.
Constant:
ACTION_PERFORMED
Method:
String getActionCommand() – It is used to know the
command(string) invoked by the user.
Java Programming RAGHU EDUCATIONAL INSTITUTIONS 22
Event Handling: sources of event
AdjustmentEvent class:
An AdjustmentEvent generated when a scroll bar is
manipulated. There are six adjustment events.

Constants:
BLOCK_DECREMENT – When user clicks inside the scroll
bar to decrease its value

BLOCK_INCREMENT – When user clicks inside the scroll


bar to increase its value

TRACK – When the slider was dragged


Java Programming RAGHU EDUCATIONAL INSTITUTIONS 23
Event Handling: sources of event
AdjustmentEvent class:
Constants:
UNIT_DECREMENT – When user clicks the end button to
decrease its value

UNIT_INCREMENT – When user clicks the end button to


increase its value

ADJUSTMENT_VALUE_CHANGED – Indicates change


has occurred
Method:
int getValue() – Gives the value of the scroll bar at current
position
Java Programming RAGHU EDUCATIONAL INSTITUTIONS 24
Event Handling: sources of event
ComponentEvent class:
A ComponentEvent generated when the size, position
or visibility of a component is changed.

Constants:
COMPONENT_HIDDEN – When component hidden
COMPONENT_SHOWN – When component shown
COMPONENT_MOVED – When component moved
COMPONENT_RESIZED – When component resized

Method:
Component getComponent() – It returns the component that
generated an event
Java Programming RAGHU EDUCATIONAL INSTITUTIONS 25
Event Handling: sources of event
ContainerEvent class:
A ContainerEvent is generated when a component is
added or removed from a container.
Constants:
COMPONENT_ADDED
COMPONENT_REMOVED

FocusEvent class:
A FocusEvent is generated when a component gained
or lost input focus.
Constants:
FOCUS_GAINED
FOCUS_LOST
Java Programming RAGHU EDUCATIONAL INSTITUTIONS 26
Event Handling: sources of event
InputEvent class:
The abstract InputEvent is a sub class of
ComponentEvent and is a super class for KeyClass and
MouseEvent class.

ItemEvent class:
An ItemEvent is generated when a Checkbox or a list-
item or when a checkable menu-item is selected or de-
selected.
Constants:
SELECTED – When user select an item
DESELECTED – When user deselect an item
Java Programming RAGHU EDUCATIONAL INSTITUTIONS 27
Event Handling: sources of event
ItemEvent class:
Method:
getItem() – Returns the reference of the selected item
getStateChange() – Returns the state change of the item
KeyEvent class: generated when keyboard input occurs.
Constants:
KEY_PRESSED – When any key pressed
KEY_TYPED – When a character key is pressed
KEY_RELEASED – When a pressed or typed key is released
Methods:
int getKeyCode() –To know the code of the key pressed or
typed
char getKeyChar() – To know the character of the key typed.
Java Programming RAGHU EDUCATIONAL INSTITUTIONS 28
Event Handling: sources of event
MouseEvent class:
There are several events generated by the mouse. They
are listed below:

Constants:
MOUSE_CLICKED – When clicked the mouse
MOUSE_DRAGGED – Keeps the mouse clicked then move
it
MOUSE_ENTERED – When mouse entered a component
MOUSE_EXITED – When mouse exited a component
MOUSE_MOVED – When mouse is moved
MOUSE_PRESSED – When mouse is pressed
MOUSE_RELEASED – Mouse is released after the pressing
Java Programming RAGHU EDUCATIONAL INSTITUTIONS 29
Event Handling: sources of event
MouseEvent class: Methods:
int getX() – Returns the x-coordinate value of the cursor position
int getY() – Returns the y-coordinate value of the cursor position
Point getPoint() – Returns x&y coordinate values of the cursor
position. After that we can use Point_reference.x and
Point_reference.y to get the coordinates.
int getClickCount() – Returns the number of mouse clicks
MouseWheelEvent class:
This is generated by the mouse wheel.
Constants:
WHEEL_BLOCK_SCROLL – When page-up or page-down
WHEEL_UNIT_SCROLL – When line-up or line-down
occurred
Java Programming RAGHU EDUCATIONAL INSTITUTIONS 30
Event Handling: sources of event

TextEvent class:
These events are generated when the text character of
text fields and text areas are modified or entered.
Constants:
TEXT_VALUE_CHANGED – When the value of text
component is modified

WindowEvent class:
There are ten types of events generated by the window.

Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 31


Event Handling: sources of event
WindowEvent class:
Constants:
WINDOW_ACTIVATED
WINDOW_OPENED
WINDOW_CLOSING
WINDOW_CLOSED
WINDOW_DEACTIVATED
WINDOW_ICONIFIED
WINDOW_DEICONIFIED
WINDOW_GAINED_FOCUS
WINDOW_LOST_FOCUS
WINDOW_STATE_CHANGED
Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 32
Event Handling: sources of event
user interface components generate events as described below. They are
the sources of events.

Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 33


Event Handling: Event Listeners
Event Listeners are created by implementing one or more
interfaces defined by java.awt.event.* package. When an
event occurrs, the event source invokes the appropriate
method defined by the listener and provides an event
reference as its argument.

ActionListener Interface:
This interface defines the method actionPerformed()
that is invoked when an action event occurs.

public void actionPerformed(ActionEvent ae)

Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 34


Event Handling: Event Listeners
AdjustmentListener Inteface:
It defines adjustmentValueChanged() method that is
invoked when an adjustment event occurs.
public void adjustmentValueChanged(AdjustmentEvent ae)

ComponentListener Interface:
It defines four methods which are invoked when component
event occurred.
public void componentResized(ComponentEvent ce)
public void componentMoved(ComponentEvent ce)
public void componentShown(ComponentEvent ce)
public void componentHidden(ComponentEvent ce)
Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 35
Event Handling: Event Listeners

ContainerListener Interface:
It defines two methods to track the container events.
public void componentAdded(ContainerEvent ce)
public void componentRemoved(ContainerEvent ce)

FocusListener Interface:
It defines two methods to track the keyboard focus over the
component.
public void focusGained(FocusEvent fe)
public void focusLost(FocusEvent fe)

Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 36


Event Handling: Event Listeners

ItemListener Interface:
It defines one method to track the changes of an item.
public void itemStateChanged(ItemEvent ie)

KeyListener Interface:
It defines three methods to track the key events.
public void keyPressed(KeyEvent ke)
public void keyTyped(KeyEvent ke)
public void keyReleased(KeyEvent ke)

Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 37


Event Handling: Event Listeners
MouseListener Interface:
It defines five methods to track the mouse events except
dragged and moved.
public void mouseEntered(MouseEvent me)
public void mouseExited(MouseEvent me)
public void mouseClicked(MouseEvent me)
public void mousePressed(MouseEvent me)
public void mouseReleased(MouseEvent me)
MouseMotionListener Interface:
It defines two methods to track the mouse dragging and
mouse moving events.
public void mouseDragged(MouseEvent me)
public void mouseMoved(MouseEvent me)
Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 38
Event Handling: Event Listeners
MouseWheelListener Interface:
It defines a method to track the mouse wheel events.
public void mouseWheelMoved(MouseWheelEvent mwe)

TextListener Interface:
It defines a method to track the text event.
public void textValueChanged(TextEvent te)

WindowFocusListener Interface:
It defines methods to track the window focus events.
public void windowGainedFocus(WindowEvent we)
public void windowLostFocus(WindowEvent we)
Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 39
Event Handling: Event Listeners
WindowListener Interface:
It defines the methods to track all the window events except
focus events of the window.
public void windowActivated(WindowEvent we)
public void windowDeactivated(WindowEvent we)
public void windowOpened(WindowEvent we)
public void windowClosing(WindowEvent we)
public void windowClosed(WindowEvent we)
public void windowIconified(WindowEvent we)
public void windowDeiconified(WindowEvent we)

Program to track mouse events


Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 40
Event Handling: Adapter classes

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

• We can define a new class act as an event listener by


extending one of the adapter classes and implementing only
those events in which we are interested.

Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 41


Event Handling: Adapter classes
The following are the adapter classes and their respective
event listeners:

program to track mouse entered and mouse dragged using


adapter classes
Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 42
Event Handling: inner classes

• Inner class is a nested class which is defined inside another


class without static keyword.

• Simply, inner class is a non-static nested class. Inner classes


are used to simplify the code when using event adapter class.

program to track mouse entered and mouse dragged using


inner classes

Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 43


Abstract Window Toolkit: Introduction
• The AWT is a tool kit which contains numerous classes and
methods that allows us to create and manage windows.

• It is also the foundation upon which Swing is built. It is to


create stand-alone or Graphical User Interface (GUI) Based
applications. AWT is used to create and manage windows,
manage fonts, output text, and utilize graphics.

• The AWT classes are contained in the java.awt package. It is


one of Java’s largest packages. Fortunately, because it is
logically organized in a top-down, hierarchical fashion, it is
easier to understand and use.
Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 44
AWT: Components & Containers
A graphical user interface is built of graphical elements
called components. Typical components include such items
as buttons, scrollbars, and text fields.

Components allow the user to interact with the


program and provide the user with visual feedback about the
state of the program. In the AWT, all user interface
components are instances of class Component or one of its
subtypes.

Types of components:
Button, Canvas, Checkbox, Choice, Label, List,
Scrollbar, TextArea, and TextField.
Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 45
AWT: Components & Containers
Containers:
• Components do not stand alone, but rather are found within
containers. Containers contain and control the layout of
components.

• Containers are themselves components, and can thus be


placed inside other containers. In the AWT, all containers are
instances of class Container or one of its subtypes.

• The classes that extends Container class are known as


containers such as Frame, Dialog and Panel.

Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 46


AWT: Container

Hierarchy of Container class


Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 47
AWT: Container

Window:
The Window class creates a top-level window. A top-
level window is not contained within any other object; it sits
directly on the desktop. Generally, we won’t create Window
objects directly. Instead, we will use a subclass of Window
called Frame, described next.

Frame:
Frame encapsulates what is commonly thought of as a
window. It is a subclass of Window and has a title bar, menu
bar, borders, and resizing corners.
Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 48
AWT: Container

The Dialog control represents a top level window with


a border and a title used to take some form of input from the
user. It inherits the Window class. Unlike Frame, it doesn't
have maximize and minimize buttons.

The Panel class is a concrete subclass of Container. In


essence, a Panel is a window that does not contain a title bar,
menu bar, or border. This is why we don’t see these items
when an applet is run inside a browser. When we run an
applet using an applet viewer, the applet viewer provides the
title and border.
Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 49
AWT: Button Component
Button is a control component that has a label and generates
an event when pressed and released.
Constructors:
Button() -Constructs a button with an empty string for its
label.
Button(String text) -Constructs a new button with specified
label.

Methods:
void addActionListener(ActionListener l) -Adds the
specified action listener to receive action events from this
button.
String getLabel() -Gets the label of this button.
Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 50
AWT: Button Component

Methods:
void setLabel(String label) -Sets the button's label to be the
specified string.

String getActionCommand() -Returns the command name


of the action event fired by this button.

void setActionCommand(String command) -Sets the


command name for the action event fired by this button.

Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 51


AWT: Label Component
A label displays a single line of read-only text. However the
text can be changed by the application programmer but
cannot be changed by the end user in any way.
Label is a passive control because it does not create any event

Following are the fields for java.awt.Component class:


static int CENTER -- Indicates that the label should be
centered.
static int LEFT -- Indicates that the label should be left
justified.
static int RIGHT -- Indicates that the label should be right
justified.
Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 52
AWT: Label Component

Constructors:

Label() - Constructs an empty label.

Label(String text) -Constructs a new label with the specified


string of text, left justified.

Label(String text, int alignment)-Constructs a new label


that presents the specified string of text with the specified
alignment.

Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 53


AWT: Checkbox Component
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.

Constructors of Checkbox:
Checkbox( ) –creates checkbox with empty label
Checkbox(String str) –creates checkbox with label
Checkbox(String str, boolean on) - creates checkbox with
label and initially can put a check mark
Checkbox(String str, boolean on, CheckboxGroup cbGroup)–
used to create Radio Button
Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 54
AWT: Checkbox Component
Constructors of Checkbox:
Checkbox(String str, CheckboxGroup cbGroup, boolean on)
- used to create Radio Button and selects the one radio button
initially.

Methods of the Checkbox:


boolean getState( ) –used to get the State of the Checkbox
void setState(boolean on) –used to set the state of the
Checkbox
String getLabel( ) –used to get the label present with the
checkbox
void setLabel(String str) –used to set the label to the
checkbox when it is created using empty constructor.
Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 55
AWT: Radio buttons (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

Check box groups are objects of type CheckboxGroup. Only


the default constructor is defined, which creates an empty
group.
Methods:
Checkbox getSelectedCheckbox( ):
To know which checkbox is selected
void setSelectedCheckbox(Checkbox which):
To set a checkbox
Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 56
AWT: Choice Component

The Choice class is used to create a pop-up list of items


from which the user may choose. It is also called as
Combobox. Thus, a Choice control is a form of menu.

When inactive, a Choice component takes up only


enough space to show the currently selected item. When the
user clicks on it, the whole list of choices pops up, and a new
selection can be made.

Choice only defines the default constructor, which creates an


empty list.
Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 57
AWT: Choice Component
Methods:
void add(String name)
Here, name is the name of the item being added.
getSelectedItem( ) method returns a string containing the
name of the item
getSelectedIndex( ) returns the index of the item. The first
item is at index 0.
int getItemCount( ) returns the number of items

void select(int index) used to select item based on index.

void select(String name) used to select item based on name.


Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 58
AWT: List Component
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.
Constructors:
1. List( ):
used to create List, only one item can be selected at a time
2. List(int numRows) - the value of numRows specifies the
number of entries in the list that will always be visible.
3. List(int numRows, boolean multipleSelect)
if multipleSelect is true, then the user may select two or more
items at a time.
Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 59
AWT: List Component
Methods:
1. void add(String name) -adds an item to the list at the end.
2. void add(String name, int index) – adds at specified index.
3. String getSelectedItem( ) –gets the selected item
4. int getSelectedIndex( ) -gets the index of the item selected
5. String[] getSelectedItems() - get all the selected items.
6. int[] getSelectedIndexes() -get all indices selected
7. int getItemCount( ) -used to get number of the items
8. void select(int index) -used to set the current item as
selected item.

Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 60


AWT: TextField Component
The TextField class implements a single-line text-entry area,
usually called an edit control.

Constructors:
1. TextField( ) used to create default text editor
2. TextField(int numChars) used to create a text filed with
some number of characters length.
3. TextField(String str)
used to create a text field with string in it.
4. TextField(String str, int numChars)
used to create text filed with string in it and also specified
number of characters length.
Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 61
AWT: TextField Component
Methods:
1. String getText( ) -used to get the text from the text field
2. void setText(String str) -used to set the text to the text field
3. String getSelectedText( ) -used to get the selected text
4. void select(int startIndex, int endIndex) -used to select the
characters starting from startindex to the endindex.
5. void setEchoChar(char ch) -used to create passwords.
Actual characters are not shown.
6. char getEchoChar( ) -used to obtain the echo characters.
Program to demonstrate Button, Label and TextField

Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 62


AWT: TextArea Component
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.
Constructors:
1. TextArea( ) -used to create default text area
2. TextArea(int rows, int cols ) -used to create text area with
specified number of rows and columns
3. TextArea(String str) -creates text area with default string.
4. TextArea(String str, int numLines, int numChars) -text area
with specified no of rows and cols with default string in it.
5. TextArea(String str, int numLines, int numChars, int
sBars) –used to create text area with scroll bars also.
Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 63
AWT: TextArea Component
TextArea supports getText( ), setText( ), getSelectedText( ),
select( ), isEditable( ), and setEditable( ) methods which are
already discussed.

Methods:
1. void append(String str) - appends at the end of the current
text area
2. void insert(String str, int index) -inserts the string at the
specified index
3. void replaceRange(String str, int startIndex, int endIndex )-
To replace text, call replaceRange( ). It replaces the
characters from startIndex to endIndex–1, with the
replacement text passed in str.
Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 64
AWT: Layouts
Program to demonstrate AWT controls

• All of the components that we have shown so far have been


positioned by the default layout manager.

• A layout manager is an instance of any class that


implements the LayoutManager interface. Layout manager is
set by the setLayout( ) method. If no call to setLayout( ) is
made, then the default layout manager is used.

• Whenever a container is resized (or sized for the first time),


the layout manager is used to position each of the
components within it.
Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 65
AWT: Layouts
The setLayout( ) method has the following general form:
void setLayout(LayoutManager layoutObj)

Here, layoutObj is a reference to the desired layout


manager. To disable the layout manager and position
components manually, pass null for layoutObj. But if we do
this, we will need to determine the shape and position of each
component manually, using the setBounds() method defined
by Component.

The LayoutManagers are used to arrange components


in a particular manner. LayoutManager is an interface that is
implemented by all the classes of layout managers.
Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 66
AWT: FlowLayout
The FlowLayout is used to arrange the components in a line,
one after another (in a flow). It is the default layout of applet
or panel.

Constructors of FlowLayout class:


1. FlowLayout(): creates a flow layout with centered
alignment and a default 5 unit horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given
alignment and a default 5 unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow
layout with the given alignment and the given horizontal and
vertical gap.
Program to demonstrate flow layout
Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 67
AWT: BorderLayout
The BorderLayout is used to arrange the components in five
regions: north, south, east, west and center. Each region
(area) may contain one component only. The BorderLayout
provides five constants for each region:
1. public static final int BorderLayout.NORTH
2. public static final int BorderLayout.SOUTH
3. public static final int BorderLayout.EAST
4. public static final int BorderLayout.WEST
5. public static final int BorderLayout.CENTER
Constructor:
BorderLayout(): creates a border layout but with no gaps
between the components.
Program to demonstrate border layout
Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 68
AWT: GridLayout
GridLayout lays out components in a two-dimensional grid.
When we instantiate a GridLayout, we define the number of
rows and columns.

Constructors:
1. GridLayout():
2. GridLayout(int rows, int columns):
3. GridLayout(int rows, int columns, int hgap, int vgap):
creates a grid layout with the given rows and columns along
with given horizontal and vertical gaps.

Program to demonstrate grid layout


Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 69
AWT: CardLayout
Using CardLayout class The CardLayout class manages the
components in such a manner that only one component is
visible at a time. It treats each component as a card that is
why it is known as CardLayout.

Constructors:
1. CardLayout(): creates a card layout with zero horizontal
and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout
with the given horizontal and vertical gap.

Program to demonstrate card layout


Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 70
AWT: Menu

A top-level window can have a menu bar associated


with it. Amenu bar displays a list of top-level menu choices.
Each choice is associated with a drop-down menu. This
concept is implemented in AWT by the following classes:
MenuBar, Menu, and MenuItem.

Menu class Constructors:


1. Menu( ) - creates an empty menu
2. Menu(String optionName) - creates a menu with some
string

Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 71


AWT: Menu
Items are added to a menu in the order in which the
calls to add( ) take place. The item is returned. Once we have
added all items to a Menu object, we can add that object to
the menu bar by using this version of add( ) defined by
MenuBar
Menu add(Menu menu)
Procedure:
1. Create a Menu
2. Add items to the Menu which are created using MenuItem
class.
3. Add Menu to the MenuBar.
4. Add MenuBar to the frame.
Program to demonstrate menu
Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 72
AWT: Scrollbar
Scroll bars are used to select continuous values between a specified
minimum and maximum. Scroll bars may be oriented horizontally or
vertically.

Scrollbar( )
Scrollbar(int style)
Scrollbar(int style, int initialValue, int thumbSize, int min, int max)

• If style is Scrollbar.VERTICAL, a vertical scroll bar is created. If style


is Scrollbar.HORIZONTAL, the scroll bar is horizontal.
• The initial value of the scroll bar is passed in initialValue.
• The number of units represented by the height of the thumb is passed
in thumbSize.
• The minimum and maximum values for the scroll bar are specified by
min and max.
Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 73
AWT: Scrollbar
Scroll bars are used to select continuous values between a specified
minimum and maximum. Scroll bars may be oriented horizontally or
vertically.

Scrollbar( )
Scrollbar(int style)
Scrollbar(int style, int initialValue, int thumbSize, int min, int max)

• If style is Scrollbar.VERTICAL, a vertical scroll bar is created. If style


is Scrollbar.HORIZONTAL, the scroll bar is horizontal.
• The initial value of the scroll bar is passed in initialValue.
• The number of units represented by the height of the thumb is passed
in thumbSize.
• The minimum and maximum values for the scroll bar are specified by
min and max.
Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 74
AWT: Scrollbar
If we construct a scroll bar by using one of the first two
constructors, then we need to set its parameters by using
setValues(), shown here, before it can be used:

void setValues(int initialValue, int thumbSize, int min, int


max)

To set the new value, call setValue(int newValue).


To obtain the current value, call getValue()

Program to demonstrate Scrollbar

Program to interact with files using awt


Java Proramming RAGHU EDUCATIONAL INSTITUTIONS 75

You might also like