0% found this document useful (0 votes)
37 views

Unit 4 - 1 - Awt Components or Controls

Uploaded by

navyamahamkali54
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

Unit 4 - 1 - Awt Components or Controls

Uploaded by

navyamahamkali54
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 41

AWT Controls (or) AWT Components

 Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-


based applications 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 are using the resources of OS.
 These controls are subclasses of Component.
 The AWT supports the following types of controls:

o Labels
o Push buttons
o Check boxes
o Choice lists
o Lists
o Scroll bars
o Text editing

Adding and Removing Controls

To include a control in a window, you must add it to the


window. To do this, you must first create an instance of
the desired control and then add it to a window by
calling add( ), which is defined by Container.
The add( ) method has several forms. The following
form is the
one that is used for the first part of this chapter:

Component add(Component compObj)

Here, compObj is an instance of the control that you


want to add. A reference to compObj is returned.

Once a control has been added, it will automatically be


visible whenever its parent window is displayed.

Sometimes you will want to remove a control from a


window when the control is no longer needed.
To do this, call remove( ).

This method is also defined by Container. It has this


general form:

void remove(Component obj)

Here, obj is a reference to the control you want to


remove. You can remove all controls by calling
removeAll( ).

Responding to Controls

Except for labels, which are passive, all controls


generate events when they are accessed by the user.
For example, when the user clicks on a push button, an
event is sent that identifies the push button. In general,
your program simply implements the appropriate
interface and then registers an event listener for each
control that you need to monitor. As explained in
Chapter 22, once a listener has been installed, events
are automatically sent to it. In the sections that follow,
the appropriate interface for each control is specified.

The HeadlessException

Most of the AWT controls described in this chapter now


have constructors that can throw a
HeadlessException when an attempt is made to
instantiate a GUI component in a non-interactive
environment (such as one in which no display, mouse,
or keyboard is present). The HeadlessException was
added by Java 1.4. You can use this exception to write
code that can adapt to non-interactive environments.
(Of course, this is not always possible.) This exception
is not handled by the programs in this chapter because
an interactive environment is required to demonstrate
the 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.

Label defines the following constructors:

Label( ) throws HeadlessException


Label(String str) throws HeadlessException
Label(String str, int how) throws
HeadlessException

The first version creates a blank label.

The second version creates a label that contains the


string specified by str. This string is left-justified.

The third version creates a label that contains the


string specified by str using the alignment specified by
how. The value of how must be one of these three
constants:

Label.LEFT, Label.RIGHT, or Label.CENTER.

You can set or change the text in a label by using the


setText( ) method.

You can obtain the current label by calling getText( ).

These methods are shown here:

void setText(String str)


String getText( )

For setText( ), str specifies the new label. For


getText( ), the current label is returned.

You can set the alignment of the string within the label
by calling setAlignment( ).

To obtain the current alignment, call getAlignment( ).


The methods are as follows:

void setAlignment(int how)


int getAlignment( )

Here, how must be one of the alignment constants


shown earlier.

The following example creates three labels and adds


them to an applet window:

// Demonstrate Labels
import java.awt.*;
import java.applet.*;
/*
<applet code="LabelDemo" width=300 height=200>
</applet>
*/

public class LabelDemo extends Applet


{
Lable one,two,three;

public void init()


{
one = new Label("One",Label.RIGHT);
two = new Label("Two");
three = new Label("Three");

// add labels to applet window


add(one);
add(two);
add(three);

}
}

Here is the window created by the LabelDemo applet.


Notice that the labels are organized in the window by
the default layout manager. Later, you will see how to
control more precisely the placement of the labels.
Buttons

Perhaps 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
defines these two constructors:

Button( ) throws HeadlessException


Button(String str) throws HeadlessException
The first version creates an empty button.
The second creates a button that contains str as a
label.

After a button has been created,

you can set its label by calling setLabel( ).


You can retrieve its label by calling getLabel( ).

These methods are as follows:

void setLabel(String str)


String getLabel( )

Here, str becomes the new label for the button.

How to Handle Buttons:

Each time a button is pressed, an action event is


generated. This is sent to any listeners that previously
registered an interest in receiving action event
notifications from that component. Each listener
implements the ActionListener interface. That
interface defines the actionPerformed( ) method,
which is called when an event occurs.

An ActionEvent object is supplied as the argument to


this method. It contains both a reference to the button
that generated the event and a reference to the action
command string associated with the button.

By default, the action command string is the label of


the button. Usually, either the button reference or the
action command string can be used to identify the
button. (You will soonsee examples of each approach.)

Here is an example that creates three buttons labeled


“Yes”, “No”, and “Undecided”.
Each time one is pressed, a message is displayed that
reports which button has been pressed. In this version,
the action command of the button (which, by default, is
its label)is used to determine which button has been
pressed. The label is obtained by calling the
getActionCommand( ) method on the ActionEvent
object passed to actionPerformed( ).

// Demonstrate Buttons
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ButtonDemo" width=250 height=150>
</applet>
*/

public class ButtonDemo extends Applet


implements ActionListener

String msg = "";

Button yes, no, maybe;

public void init()


{
yes = new Button("Yes");
no = new Button("No");
maybe = new Button("Undecided");

add(yes);
add(no);
add(maybe);

yes.addActionListener(this);
no.addActionListener(this);
maybe.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)


{

String str = ae.getActionCommand();

if(str.equals("Yes"))
{
msg = "You pressed Yes.";
}

else if(str.equals("No"))
{
msg = "You pressed No.";
}

else
{
msg = "You pressed Undecided.";
}
repaint();
}

public void paint(Graphics g)


{
g.drawString(msg, 6, 100);
}
}

Sample output from the ButtonDemo program is


shown in Figure 24-1.As mentioned, in addition to
comparing button action command strings, you can
alsodetermine which button has been pressed, by
comparing the object obtained from the
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.
Check boxes are objects of the Checkbox class.

Checkbox supports these constructors:

Checkbox( ) throws HeadlessException

Checkbox(String str) throws HeadlessException


Checkbox(String str, boolean on) throws
HeadlessException

Checkbox(String str, boolean on, CheckboxGroup


cbGroup) throws HeadlessException

Checkbox(String str, CheckboxGroup cbGroup, boolean


on) throws HeadlessException

The first form creates a check box whose label is


initially blank. The state of the check box is unchecked.

The second form creates a check box whose label is


specified by str. The state of the check box is
unchecked.

The third form allows you to set the initial state of the
check box. If on is true, the check box is initially
checked; otherwise, it is cleared.

The fourth and fifth forms create a check box whose


label is specified by str and whose group is specified by
cbGroup. If this check box is not part of a group, then
cbGroup must be null. (Check box groups are
described in the next section.) The value of on
determines the initial state of the check box.

To retrieve the current state of a check box, call


getState( ).
To set its state, call setState( ).

You can obtain the current label associated with a


check box by calling
getLabel( ).
To set the label, call setLabel( ). These methods are
as follows:

boolean getState( )
void setState(boolean on)
String getLabel( )
void setLabel(String str)

Here, if on is true, the box is checked. If it is false, the


box is cleared. The string passed in str becomes the
new label associated with the invoking check box.

How to Handle Check Boxes:

Each time a check box is selected or deselected, an


item event is generated. This is sent to any listeners
that previously registered an interest in receiving item
event notifications from that component. Each listener
implements the ItemListener interface.

That interface defines the itemStateChanged( )


method.

An ItemEvent object is supplied as the argument to


this method. It contains information about the event
(for example, whether it was a selection or
deselection).

The following program creates four check boxes. The


initial state of the first box is checked. The status of
each check box is displayed. Each time you change the
state of a check box, the status display is updated.
// Demonstrate check boxes.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="CheckboxDemo" width=250
height=200>
</applet>
*/
public class CheckboxDemo extends Applet
implements ItemListener
{
String msg = "";

Checkbox winXP, winVista, solaris, mac;

public void init()


{
winXP = new Checkbox("Windows XP",true);
winVista = new Checkbox("Windows Vista",true);
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");

add(winXP);
add(winVista);
add(solaris);
add(mac);

winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);

}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}

// Display current state of the check boxes.

public void paint(Graphics g)


{
msg = "Current state: ";
g.drawString(msg, 6, 80);

msg = " Windows XP: " + winXP.getState();


g.drawString(msg, 6, 100);

msg = " Windows Vista: " + winVista.getState();


g.drawString(msg, 6, 120);

msg = " Solaris: " + solaris.getState();


g.drawString(msg, 6, 140);

msg = " Mac OS: " + mac.getState();


g.drawString(msg, 6, 160);
}
}
Sample output is shown in Figure 24-2.
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, because they act
like the station selector on a car radio—only one station
can be selected at any one time. To create a set of
mutually exclusive check boxes, you must first define
the group to which they will belong and then specify
that group when you construct the check boxes. Check
box groups are objects of type CheckboxGroup. Only
the default constructor is defined, which creates an
empty group.

You can determine which check box in a group is


currently selected by calling
getSelectedCheckbox( ).

You can set a check box by calling


setSelectedCheckbox( ).

These methods are as follows:


Checkbox getSelectedCheckbox( )
void setSelectedCheckbox(Checkbox which)

Here, which is the check box that you want to be


selected? The previously selected check box will be
turned off.

Here is a program that uses check boxes that are part


of a group:

// Demonstrate check box group.


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="CBGroup" width=250 height=200>
</applet>
*/
public class CBGroup extends Applet implements
ItemListener

{
String msg = "";
Checkbox winXP, winVista, solaris, mac;
CheckboxGroup cbg;

public void init()


{
cbg = new CheckboxGroup();

winXP = new Checkbox("Windows XP", cbg, false);

winVista = new Checkbox("Windows Vista", cbg,


true);
solaris = new Checkbox("Solaris", cbg, false);

mac = new Checkbox("Mac OS", cbg, false);

add(winXP);
add(winVista);
add(solaris);
add(mac);
winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
}

public void itemStateChanged(ItemEvent ie)


{
repaint();
}
// Display current state of the check boxes.

public void paint(Graphics g)


{
msg = "Current selection: ";
msg += cbg.getSelectedCheckbox().getLabel();
g.drawString(msg, 6, 100);
}
}
Output generated by the CBGroup applet is shown in
Figure 24-3. Notice that the check boxes are now
circular in shape.
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. 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. Each item in the list is a string that appears as a
left-justified label in the order it is added to the Choice
object. Choice only defines the default constructor,
which creates an empty list.

To add a selection to the list, call add( ). It has this


general form:
void add(String name)

Here, name is the name of the item being added. Items


are added to the list in the order in which calls to
add( ) occur.
To determine which item is currently selected, you may
call either getSelectedItem( ) or getSelectedIndex(
). These methods are shown here:

String getSelectedItem( )
int getSelectedIndex( )

The 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. By default, the first item
added to the list is selected.

To obtain the number of items in the list, call


getItemCount( ). You can set the currently selected
item using the select( ) method with either a zero-
based integer index or a string that will match a name
in the list. These methods are shown here:

int getItemCount( )
void select(int index)
void select(String name)

Given an index, you can obtain the name associated


with the item at that index by calling getItem( ), which
has this general form:
String getItem(int index)
Here, index specifies the index of the desired item.
Handling Choice Lists

Each time a choice is selected, an item event is


generated. This is sent to any listeners that previously
registered an interest in receiving item event
notifications from that component. Each listener
implements the ItemListener interface. That interface
defines the itemStateChanged( )
method. An ItemEvent object is supplied as the
argument to this method.
Here is an example that creates two Choice menus.
One selects the operating system.
The other selects the browser.

// Demonstrate Choice lists.


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<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


os.add("Windows XP");
os.add("Windows Vista");
os.add("Solaris");
os.add("Mac OS");

// add items to browser list


browser.add("Internet Explorer");
browser.add("Firefox");
browser.add("Opera");

// add choice lists to window


add(os);
add(browser);

// register to receive item events

os.addItemListener(this);
browser.addItemListener(this);
}

public void itemStateChanged(ItemEvent ie)


{
repaint();
}

// Display current selections.

public void paint(Graphics g)


{
msg = "Current OS: ";
msg += os.getSelectedItem();
g.drawString(msg, 6, 120);
msg = "Current Browser: ";
msg += browser.getSelectedItem();
g.drawString(msg, 6, 140);
}
}
Sample output is shown in Figure 24-4.

Using 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( ) throws HeadlessException


List(int numRows) throws HeadlessException

List(int numRows, boolean multipleSelect) throws


HeadlessException

The first version creates a List control that allows only


one item to be selected at any one time. In the second
form, the value of numRows specifies the number of
entries in the list that will always be visible (others can
be scrolled into view as needed). In the third form, if
multipleSelect is true, then the user may select two or
more items at a time. If it is false, then only one item
may be selected.

To add a selection to the list, call add( ). It has the


following two forms:
void add(String name)
void add(String name, int index)
Here, name is the name of the item added to the list.
The first form adds items to the end of the list. The
second form adds the item at the index specified by
index. Indexing begins at
zero. You can specify –1 to add the item to the end of
the list.
For lists that allow only single selection, you can
determine which item is currently selected by calling
either getSelectedItem( ) or getSelectedIndex( ).
These methods are shown here:

String getSelectedItem( )
int getSelectedIndex( )

The getSelectedItem( ) method returns a string


containing the name of the item. If more than one item
is selected, or if no selection has yet been made, null is
returned. getSelectedIndex( ) returns the index of
the item. The first item is at index 0. If more than one
item is selected, or if no selection has yet been made, –
1 is returned.

For lists that allow multiple selection, you must use


either getSelectedItems( ) or

getSelectedIndexes( ), shown here, to determine the


current selections:

String[ ] getSelectedItems( )
int[ ] getSelectedIndexes( )

getSelectedItems( ) returns an array containing the


names of the currently selected items.

getSelectedIndexes( ) returns an array containing


the indexes of the currently selected items.

To obtain the number of items in the list, call


getItemCount( ). You can set the currently selected
item by using the select( ) method with a zero-based
integer index. These methods
are shown here:

int getItemCount( )
void select(int index)

Given an index, you can obtain the name associated


with the item at that index by calling getItem( ), which
has this general form:

String getItem(int index)


Here, index specifies the index of the desired item.

Handling Lists
To process list events, you will need to implement the
ActionListener interface. Each time a List item is
double-clicked, an ActionEvent object is generated. Its
getActionCommand( ) method can be used to
retrieve the name of the newly selected item. Also,
each time an item is
selected or deselected with a single click, an
ItemEvent object is generated. Its
getStateChange( ) method can be used to determine
whether a selection or deselection triggered this event.
getItemSelectable( ) returns a reference to the
object that triggered this event.

Here is an example that converts the Choice controls


in the preceding section into List
components, one multiple choice and the other single
choice:
// Demonstrate Lists.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<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);
browser = new List(4, false);
// add items to os list
os.add("Windows XP");
os.add("Windows Vista");
os.add("Solaris");
os.add("Mac OS");
// add items to browser list
browser.add("Internet Explorer");
browser.add("Firefox");
browser.add("Opera");
browser.select(1);
// add lists to window
add(os);
add(browser);
// register to receive action events
os.addActionListener(this);
browser.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
repaint();
}
// Display current selections.
public void paint(Graphics g) {
int idx[];
msg = "Current OS: ";
idx = os.getSelectedIndexes();
for(int i=0; i<idx.length; i++)
msg += os.getItem(idx[i]) + " ";
g.drawString(msg, 6, 120);
msg = "Current Browser: ";
msg += browser.getSelectedItem();
g.drawString(msg, 6, 140);
}
}

Sample output generated by the ListDemo applet is


shown in Figure 24-5.
Managing Scroll Bars
Scroll bars are used to select continuous values
between a specified minimum and maximum.

Scroll bars may be oriented horizontally or vertically. A


scroll bar is actually a composite of several individual
parts. Each end has an arrow that you can click to
move the current value of the scroll bar one unit in the
direction of the arrow. The current value of the scroll
bar relative to its minimum and maximum values is
indicated by the slider box (or thumb) for the scroll bar.
The slider box can be dragged by the user to a new
position. The scroll bar will then reflect this value. In the
background space on either side of the thumb, the user
can
click to cause the thumb to jump in that direction by
some increment larger than 1. Typically, this action
translates into some form of page up and page down.
Scroll bars are encapsulated by the Scrollbar class.

Scrollbar defines the following constructors:

Scrollbar( ) throws HeadlessException


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

The first form creates a vertical scroll bar.


The second and third forms allow you to specify the
orientation of the scroll bar. If style is
Scrollbar.VERTICAL, a vertical scroll bar is created. If
style is Scrollbar.HORIZONTAL, the scroll bar is
horizontal.
In the third form of the constructor, 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.
If you construct a scroll bar by using one of the first two
constructors, then you need toset its parameters by
using setValues( ), shown here, before it can be used:

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


int max)

The parameters have the same meaning as they have


in the third constructor just described. To obtain the
current value of the scroll bar, call getValue( ). It
returns the current
setting. To set the current value, call setValue( ).
These methods are as follows:

int getValue( )
void setValue(int newValue)

Here, newValue specifies the new value for the scroll


bar. When you set a value, the slider box inside the
scroll bar will be positioned to reflect the new value.

You can also retrieve the minimum and maximum


values via getMinimum( ) and getMaximum( ),
shown here:

int getMinimum( )
int getMaximum( )
They return the requested quantity.

By default, 1 is the increment added to or subtracted


from the scroll bar each time it is scrolled up or down
one line. You can change this increment by calling
setUnitIncrement( ).

By default, page-up and page-down increments are 10.


You can change this value by calling
setBlockIncrement( ). These methods are shown
here:

void setUnitIncrement(int newIncr)


void setBlockIncrement(int newIncr)

Handling Scroll Bars

To process scroll bar events, you need to implement


the AdjustmentListener interface.
Each time a user interacts with a scroll bar, an
AdjustmentEvent object is generated. Its
getAdjustmentType( ) method can be used to
determine the type of the adjustment. The types of
adjustment events are as follows:

BLOCK_DECREMENT A page-down event has been


generated.

BLOCK_INCREMENT A page-up event has been


generated.

TRACK An absolute tracking event has been generated.

UNIT_DECREMENT The line-down button in a scroll bar


has been pressed.

UNIT_INCREMENT The line-up button in a scroll bar has


been pressed.
The following example creates both a vertical and a
horizontal scroll bar. The current settings of the scroll
bars are displayed. If you drag the mouse while inside
the window, the coordinates of each drag event are
used to update the scroll bars. An asterisk is displayed
at the current drag position.

// Demonstrate scroll bars.


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<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 =
Integer.parseInt(getParameter("width"));
int height =
Integer.parseInt(getParameter("height"));
vertSB = new Scrollbar(Scrollbar.VERTICAL,
0, 1, 0, height);
horzSB = new Scrollbar(Scrollbar.HORIZONTAL,
0, 1, 0, width);
add(vertSB);
add(horzSB);
// register to receive adjustment events
vertSB.addAdjustmentListener(this);
horzSB.addAdjustmentListener(this);
addMouseMotionListener(this);
}
public void
adjustmentValueChanged(AdjustmentEvent ae) {
repaint();
}
// Update scroll bars to reflect mouse
dragging.
public void mouseDragged(MouseEvent me) {
int x = me.getX();
int y = me.getY();
vertSB.setValue(y);
horzSB.setValue(x);
repaint();
}
// Necessary for MouseMotionListener
public void mouseMoved(MouseEvent me) {
}
// Display current value of scroll bars.
public void paint(Graphics g) {
msg = "Vertical: " + vertSB.getValue();
msg += ", Horizontal: " + horzSB.getValue();
g.drawString(msg, 6, 160);
// show current mouse drag position
g.drawString("*", horzSB.getValue(),
vertSB.getValue());
}
}
Sample output from the SBDemo applet is shown in
Figure 24-6.

Using a 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. TextField is a subclass of
TextComponent.

TextField defines the following constructors:


TextField( ) throws HeadlessException

TextField(int numChars) throws HeadlessException

TextField(String str) throws HeadlessException

TextField(String str, int numChars) throws


HeadlessException

The first version creates a default text field.

The second form creates a text field that is numChars


characters wide.

The third form initializes the text field with the string
contained
in str.
The fourth form initializes a text field and sets its width.

TextField (and its superclass TextComponent)


provides several methods that allow you to utilize a
text field.

To obtain the string currently contained in the text


field, call getText( ).

To set the text, call setText( ). These methods are as


follows:

String getText( )
void setText(String str)
Here, str is the new string.

The user can select a portion of the text in a text field.


Also, you can select a portion of text under program
control by using select( ).
Your program can obtain the currently selected text by
calling getSelectedText( ). These methods are shown
here:

String getSelectedText( )
void select(int startIndex, int endIndex)
getSelectedText( ) returns the selected text. The
select( ) method selects the characters beginning at
startIndex and ending at endIndex–1.

You can control whether the contents of a text field


may be modified by the user by calling setEditable( ).
You can determine editability by calling isEditable( ).
These methods
are shown here:

boolean isEditable( )
void setEditable(boolean canEdit)

isEditable( ) returns true if the text may be changed


and false if not. In setEditable( ), if canEdit is true,
the text may be changed. If it is false, the text cannot
be altered.

There may be times when you will want the user to


enter text that is not displayed, such as a password.
You can disable the echoing of the characters as they
are typed by calling

setEchoChar( ). This method specifies a single


character that the TextField will display when
characters are entered (thus, the actual characters
typed will not be shown).

You can check a text field to see if it is in this mode


with the echoCharIsSet( ) method.
You can retrieve the echo character by calling the
getEchoChar( ) method. These methods are as
follows:

void setEchoChar(char ch)

boolean echoCharIsSet( )

char getEchoChar( )

Here, ch specifies the character to be echoed.

Handling a TextField

Since text fields perform their own editing functions,


your program generally will not respond to individual
key events that occur within a text field. However, you
may want to respond when the user presses ENTER.
When this occurs, an action event is generated. Here is
an example that creates the classic user name and
password screen:

// Demonstrate text field.


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<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: ", Label.RIGHT);
Label passp = new Label("Password: ",
Label.RIGHT);
name = new TextField(12);
pass = new TextField(8);
pass.setEchoChar('?');
add(namep);
add(name);
add(passp);
add(pass);
// register to receive action events
name.addActionListener(this);
pass.addActionListener(this);
}
// User pressed Enter.
public void actionPerformed(ActionEvent ae) {
repaint();
}
public void paint(Graphics g) {
g.drawString("Name: " + name.getText(), 6, 60);
g.drawString("Selected text in name: "
+ name.getSelectedText(), 6, 80);
g.drawString("Password: " + pass.getText(), 6,
100);
}
}
Sample output from the TextFieldDemo applet is
shown in Figure 24-7.
The hierarchy of Java AWT classes are given below.

You might also like