Chapter 7 -- The Order Entry System: Entry Fields,
Labels, and Validation
Chapter 7
The Order Entry System: Entry Fields,
Labels, and Validation
CONTENTS
The preceding two chapters covered the basic concepts behind applets
and many of the components in the AWT. This chapter covers the
remaining components, including those specific to text input and
output. There are multiple components dealing with text including
labels, text fields, and text areas. The implementation and function
of each one of these components are detailed in this chapter.
In this chapter, you also take some more steps toward completing
the Order Entry System. This chapter extends the system to include
the components discussed in this chapter and handles them appropriately.
The chapter also fills in some of the "holes," such
as the unfinished updateValues
method, and activates the Clear button.
Finally, the chapter covers the methods of password entry and
identification, which are very important in the applet design
business. This same section also covers data validation in the
entry fields.
The AWT components covered in this chapter deal with text, both
input and output. The generic AWT text output components are labels.
They are simply unformatted text that can be added to a container.
Note: |
There are also other means to insert text into AWT programs. These are, however, graphical and are covered in Chapter 9, "The Order Entry System: Adding Graphics and a Logo." If you want to do this, look for the
drawString() method in the index. Since these methods function to draw graphics onto components and are not components themselves, they are saved for later.
|
Labels are simple components. You provide a string, and it gets
placed onto an applet or your panel. Labels are used to label
your other components or features in your panel. Since labels
do nothing, there is no need to handle events generated by them.
As such, you will notice that there are no Events
related to labels in the preceding chapter. Labels are limited
in their ability to change fonts and their plain unattractiveness
when placed together.
Adding labels to your AWT programs is simple. In fact, doing so
is almost embarrassing because it is so easy. The following line
adds a component containing the string "It's
so easy." to a container:
add(new Label("It's so easy."));
Of course, if you want to have the ability to change the string
displayed on your label at a later time, you declare a variable
of the label type and then
add it to your container using add.
The following lines do just that:
Label ALabel = new Label("It's so
easy."));
add(ALabel);
The following are the three major constructors for creating labels:
ALabel = new Label();
BLabel = new Label("The String You Want");
CLabel = new Label("The String You Want", AlignConstant);
In the first constructor, ALabel
is allocated to be an instance of Label
with no string or alignment set. In the next two constructors,
the first parameter is the string you want to have displayed.
In the third constructor, the AlignConstant
is one of Label.LEFT, Label.RIGHT,
or Label.CENTER. Each different
constant sets the alignment of the text in the label component.
Default alignment is left.
There are some useful methods when dealing with instances of the
Label class. The most important
is the setText method. The
setText method takes a parameter
of a string and then changes the text on the label to the string.
The following line changes the text of an instance of the Label
class:
ALabel.setText("This is how we do
it.");
That's it. You can also get the text of a label with its getText
method. It returns an instance of the String
class, as follows:
AString = ALabel.getText();
You can also do the same with the alignment of a label. The setAlignment
and getAlignment methods
allow this. The setAlignment
method accepts one of the alignment constants in the Label
class (Label.LEFT, Label.RIGHT,
Label.CENTER). The getAlignment
method returns one of these same constants.
The code for the CrazySimpleLabel
applet is shown in Listing 7.1.
Listing 7.1. The CrazySimpleLabel
applet code.
import java.awt.*;
import java.applet.*;
public class CrazySimpleLabel extends Applet {
private Label LabelA;
private Label LabelB;
private Label LabelC;
public void init() {
// Allocate a
new Label.
LabelA = new Label();
// Set the label
string.
LabelA.setText(" I
want this text.");
// Set the label
alignment.
LabelA.setAlignment(Label.RIGHT);
// Add the Label
add(LabelA);
// Allocate a
new Label.
LabelB = new Label("
I want this text. ");
// Set the label
alignment.
LabelB.setAlignment(Label.CENTER);
// Add the Label
add(LabelB);
// Allocate a
new Label, set the text and alignment.
LabelC = new Label("I
want this text. ", Label.LEFT);
// Add the Label
add(LabelC);
}
}
This small applet creates and inserts three different labels onto
the applet panel. Each one is aligned differently. Figure 7.1
shows the output from this applet when viewed with the AppletViewer.
Figure 7.1 : The output from the CrazySimpleLabel applet, which demonstrates the lable class of the AWT.
You may question the extra spaces in some of the label definitions
here. Well, I cheated a little to make a point. Otherwise, making
the alignment stand out distinctly is tough. But if you remove
the spaces from the strings in Listing 7.1, you can see a very
small difference-though it is not immediately apparent.
Text fields allow text input from the user. They allow the full
mouse editing capabilities to which you are accustomed on Windows-based
systems. This includes the cutting and pasting specific to each
platform. Text fields have a limited width. However, text fields
do scroll to follow where the cursor is. There are four constructors
for the TextField class.
The following creates a text entry field with a width of zero
characters:
ATextField = new TextField();
The following creates a text entry field of WidthInChar
(an int) characters wide:
BTextField = new TextField(WidthInChar);
The following line creates a text field of size zero with the
initial text InitialText
(an instance of the String
class):
CTextField = new TextField(InitialText);
The following line constructs a text field with the initial text
InitialText and of size WidthInChar.
It is the one you will find most convenient to use.
DTextField = new TextField(InitialText,
WidthInChar);
There are also a number of useful methods when dealing with TextFields.
Most important is the getText()
method, which follows. It returns the text in the field as an
instance of the String class.
String AString = ATextField.getText();
To set the text in a text field, you do the same thing as with
labels
ATextField.setText(AString);
where AString is an instance
of the String class. You
can also check the width of an instance of the TextField
class with the getColumns()
method. This function returns the width of the text field in characters
as an integer.
Also, when users are editing the text in the field, you can set
the selected text for them. On most systems, this is some kind
of highlight, such as inversion of the text and background colors.
Either way, the AWT provides two methods to select the text in
an entry field. The selectAll()
method selects all the text in a field. The select(StartPos,
FinishPos) method allows you to specify the beginning
and ending integers between which you want to have the text selected.
The setEditable(ABoolean)
and IsEditable() functions
in the TextField class allow
you to set and test the editability of the text field. If IsEditable()
returns true, then the user
is able to make changes in the field. However, if it returns false,
the text is "locked" in the field and not changeable.
To set what IsEditable()
returns, use the setEditable
method, which takes a variable of type boolean
as its only parameter.
The textField class generates
a call to your action method
when the user presses the Enter or Return key when the user's
focus is on the text field. Other than that, no events are generated
by the textField class. To
handle the events generated by text fields, your action
method should contain code of the following format:
public boolean action(Event InEvent,
Object InArgument) {
.
.
if (InEvent.target == YourTextField) {
// Do what you
want here. . .
return true;
} else . . .
.
}
This format is included in the TextFieldCrazy
applet code, which uses text fields as shown in the Listing 7.2.
The corresponding output is shown in Figure 7.2 (remember that
the line numbers are for reference only).
Figure 7.2 : The CrazyTextField applet, which demonstrates handling events generated by the TextField class.
Listing 7.2. The TextFieldCrazy
applet code.
1. import java.awt.*;
2. import java.applet.*;
3.
4. public class CrazyTextField extends Applet {
5.
6. // A text field of width 10 with the
initial text set.
7. private TextField ATextField = new TextField("ABC",
25);
8. // A label with the text set.
9. private Label ALabel = new Label("Type
ABC in field.");
10. // The string we will
be checking against.
11. private static String AString = new
String("ABC");
12.
13. public void init () {
14. // Add the
label to the applet panel.
15. add(ALabel);
16. // Select the
text between indexes 5 and 8.
17. ATextField.select(5,
8);
18. // Add the
text field to the applet panel.
19. add(ATextField);
20.
21. }
22.
23. public boolean action(Event InEvent,
Object InParam) {
24. if (InEvent.target
== ATextField) {
25. if
(AString.equals(ATextField.getText())) {
26. ATextField.setEditable(false);
27. }
28.
return true;
29. } else return
false;
30. }
31.}
What's going on? The init()
class does all the usual stuff-adding the components to the applet
panel and doing the major setup tasks. Line 14 selects the text
between the fifth and eighth characters in the text field. Then
the action method of the
applet is called when the TextField
generates an Event. It first
checks, in line 24, to see if the event target (the event that
initiated the event) is the text field. If so, then it checks
to see if the text in the field is the text ABC.
If this is true, then it sets the field so that the user cannot
further edit the text contained within it.
Tip: |
A note on the private modifier: Java is highly object oriented. One major characteristic of object-oriented programming is the idea of data encapsulation. This means that data and variables inside of a class should not be accessible by those
outside the class (like other classes who import them). Declaring things to be private ensures that those variables aren't accessible except by methods inside the class to which they belong, even if someone wants to try to access them.
You can also set your methods and classes to be final. When they are labeled as such, they are unable to be extended or overridden by other classes. Use this when possible because it reduces errors and also increases program efficiency.
|
TextFields are great, but
what if you want to edit more than one line? That's the place
where the TextArea class
comes in.
Text areas in the AWT allow editing of multiple lines of text.
They share many of the characteristics of TextFields,
except they are extended to facilitate editing large areas of
text. There are three major constructors for the TextArea
class. The following creates an empty TextArea
of width and height zero:
ATextArea = new TextArea();
You set the width and height of the field before inserting it.
To set the width and height while declaring the field, use the
constructor
BTextArea = new TextArea(WidthInChars,
HeightInChars);
where both of the parameters are integers. To set the initial
text along with the width and the height of the text area, use
the constructor format
CTextArea = new TextArea(TextString,
WidthInChars, HeightInChars);
where the first parameter is an instance of the String
class and the remaining two parameters are integers.
There are a number of useful functions to use with the TextArea
class. The two simplest are the getColumns()
and getRows functions. They
each return an integer value representing either the width of
the text area in characters or the height in characters.
The insertText and replaceText
methods are a little more useful. The insertText
method takes the following format:
ATextArea.insertText(AString, PositionInt);
The preceding line inserts the text contained in the string
AString at position PositionInt.
The replaceText method takes
the following format:
ATextArea.replaceText(AString, StartInt,
EndInt);
The preceding line replaces the text between positions StartInt
and EndInt with the text
in AString. The appendText
method appends a string (passed as a parameter) at the end of
the current text in the text area.
When you're dealing with the user selecting text, you can use
a number of other methods. For instance, if you ask a user to
highlight a portion of text that he or she likes the best, you
can find the start and end positions of the selection getSelectionStart()
and getSelectionStop()methods.
These methods each return integers representing the first and
last positions of the selected text. If you want to get the selected
text itself, use the getSelectedText()
method, which returns an instance of the String
class. The following line of code sets the string AString
equal to the selected text in a text area:
AString = ATextArea.getSelectedText();
You can also set the selected text in a text area. The following
method does just that:
ATextArea.select(StartPos, EndPos);
where both parameters are integers. To select all the text in
the text area, you use the selectAll()
method, as follows:
ATextArea.selectAll();
Tip: |
It is risky to count on users to be able to perform the cutting and pasting of text for a couple of reasons. One, on many systems such as X Window, cutting and pasting text aren't intuitive. Two, many of the individuals using the Web these days are new to
computers, so they may not know how to cut and paste.
|
Perhaps the most difficult task when you're dealing with components
in the AWT is not creating them, but getting them active. Text
areas and text fields differ in their dealings with events. Text
areas do not generate any calls to an action
method. Instead, they generate events that are usually dealt with
by your program's handleEvent
method. Two events that you will find useful are Event.SELECT
and Event.DESELECT. A complete
listing of the Event.ids
that deal with the List class
are included in Chapter 6, "The Order
Entry System: Adding Features and Handling Events." In most
cases, you associate an event generated by another component such
as a button or a list. If you want, the Order Entry System can
associate a selection in the product list with inserting new text
about that product into the text area. Or a button labeled "Clear"
can empty the text area when its event is handled in the action
method.
To deal with text areas in your programs, include coding of the
following format in your handleEvent
method:
if (InEvent.target == YourTextArea) {
if (InEvent.id == WhatYouAreCheckingFor)
{
// Do what you
want. . .
}
}
Now that some more AWT concepts have been covered, it's time to
include a couple more features in the Order Entry System. First,
add some labels in order to help organize the applet panel into
an orderly and easy-to-follow layout. Also, incorporate some text
fields and a text area into the system. Finally, construct the
framework to handle events from these new components.
First, to add labels, include the following code:
add(new Label("Name: ");
Since most of the labels are static and don't need to be changed
after adding them, you don't generally need to declare variables
of the Label component class.
Instead, allocate a new Label
and then insert it onto the applet panel. You will add multiple
labels in this same way.
There are a couple of labels that you need to change during the
running of the applet. The total, subtotal, and price per item
need to be displayed via labels. As different choices about sizes
and products are made, these labels need to be updated. To do
this, call the updateValues
method, which was discussed last when events were generated by
these components. The updateValues
method updates all the internal values to match current settings
and choices. This method is implemented in this section.
Also, since labels need to display strings, you need to convert
the integers to an instance of the String
class. To do this, use a method of the Integer
type of Java. The following code sets a label to show a value
of 20:
ALabel.setText(Integer.toString(20));
This is applicable to the variable containing the amount of an
item to be ordered. However, some of the other variables and constants
are of the type Double. But,
you are in luck because the same conversion is possible with Doubles.
Tip: |
If you can't find something that you want to do, check out the source code for the Java library. They are in the SRC directory of your installed developer's kit. All the classes included are well documented and easy to follow. And if it looks like Greek,
then at least you tried, right?
|
To add a text field, you need to declare an instance of it as
a variable in the applet. This line creates a new instance of
TextField that is 25 characters
in width:
Private textfield nameentryfield = new
textfield(25);
By declaring it private,
you disable any access outside the applet to the variable. This
isn't necessary but is good coding practice. You also declare
the same type of text fields to enter other user information such
as city or contact information.
The Order Entry System includes a text area to allow the users
to enter any comments they may have. To declare an instance of
the TextArea that is 25 characters
wide, 4 rows tall, and with no starting text, use this line:
private TextArea CommentTextArea = new
TextArea(4, 25);
With both this text area and the other components, you include
their addition to the applet panel in the init
method.
You don't need to deal with any events generated by the labels
in the applet since the Label
class doesn't generate any events. However, you want to set the
framework for handling events from text entry fields. To do this,
add the following code segment to the action
method for each text field that you want to deal with:
if (InEvent.target == NameEntryField)
{
// What we want to do here . .
return true;
} else
Of course, the inside of the if
statement is different for each text field in the applet. For
example, the name text entry field calls a method to check to
see that there is actually a name included.
For functionality, you don't need to handle any events from the
comment text area. A method called resetValues
is also added; it resets all internal values in the
applet.
The updateValues method does
the real work of the applet. In a sense, you can look at the rest
of the program as an interface for it. It takes the input data
and computes the necessary output. The way updateValues
works is simple. First, it declares all the variables that it
needs to use. It finds the indexes of the different choices and
lists. It uses the input from the slider to compute the different
output values such as the subtotal and the total. It changes the
text in the corresponding labels on the applet panel to match
the new values. And then the runtime comes along, and when it
updates the applet panel, it changes the appearance to be what
the method just set it to.
Listing 7.3 shows the code for the Order Entry System so far.
Figure 7.3 shows the resulting Order Entry System with these additions.
Figure 7.3 : The Order Entry System with text-oriented components added.
Listing 7.3. The Order Entry
System code with text-oriented components added.
import java.awt.*;
import java.applet.*;
public class OrderEntrySystem extends Applet {
// The subtotal and total variables.
private double SubTotalOne = 0.0;
private double Total = 0.0;
// The price multipliers for each different
product size.
private double multiplierSmall = 0.5;
private double multiplierMedium = 1.0;
private double multiplierLarge = 1.5;
private double multiplierJumbo = 2.25;
// The local constant base prices.
static double ProdOneBaseValue = 1.0;
static double ProdTwoBaseValue = 1.33;
static double ProdThreeBaseValue = 1.75;
static double ProdFourBaseValue = 8.75;
// Declare all of the variables we'll
use.
private Button SubmitButton;
private Button ClearButton;
private Button QuitButton;
private Checkbox RepeatCustCheckBox;
private Checkbox MailBox;
private Checkbox EmailBox;
private Checkbox PhoneBox;
private List ProductList;
private Choice SizeChoice;
private Scrollbar OrderAmountSlider;
// The labels which will be variable and
change when
// the other selections are changed.
private Label SubTotalLabel = new Label("$0.0
");
private Label TotalLabel = new Label("$0.0
");
private Label AmountLabel = new Label("$0.0
");
private Label PricePerItemLabel = new
Label("$0.0 ");
// The entry field for the user to enter
their name.
private TextField NameEntryField = new
TextField(25);
private TextField ZipEntryField = new
TextField(5);
private TextField StreetEntryField = new
TextField(25);
private TextField CityEntryField = new
TextField(25);
// The comment entry area.
private TextArea CommentTextArea = new
TextArea(4, 25);
// Declare the init method.
public void init()
{
//
Add and create three buttons.
Button
SubmitButton = new Button("Submit");
add(SubmitButton);
Button
ClearButton = new Button("Clear");
add(ClearButton);
Button
QuitButton = new Button("Quit");
add(QuitButton);
//
Add and create the repeat customer checkbox.
Checkbox
RepeatCustCheckBox = new Checkbox("Repeat Customer?");
add(RepeatCustCheckBox);
//
Add a label to the ContactMethodGroup.
add(new
Label("How would you like to be contacted? "));
//
Declare the CheckboxGroup, and allocate space.
CheckboxGroup
ContactMethodGroup;
ContactMethodGroup
= new CheckboxGroup();
//
Create some checkboxes to put in the group.
Checkbox
EmailBox = new Checkbox("Email",ContactMethodGroup,true);
Checkbox
PhoneBox = new Checkbox("Phone",ContactMethodGroup,false);
Checkbox
MailBox = new Checkbox("US Mail",ContactMethodGroup,false);
//
Add the checkboxes into the applet panel.
add(EmailBox);
add(PhoneBox);
add(MailBox);
//
Label the item list.
add(new
Label("Products"));
//
Create the list, 4 items visible, no multiple
//
selections.
ProductList
= new List(4, false);
//
AddItems to the List.
ProductList.addItem("Oscar");
ProductList.addItem("Lionhead");
ProductList.addItem("Jack
Dempsey");
ProductList.addItem("Angelfish");
//
Add the List to the Applet panel.
add(ProductList);
//
Add a label to the choice of sizes.
add(new
Label("Size:"));
//
Create the Choice box.
SizeChoice
= new Choice();
//
AddItems to the List.
SizeChoice.addItem("Jumbo");
SizeChoice.addItem("Large");
SizeChoice.addItem("Medium");
SizeChoice.addItem("Small");
//
Add the Choice to the Applet panel.
add(SizeChoice);
//
Add a label to the slider.
add(new
Label("Amount:"));
//
Create a vertical slider, initial value of 0,
//
minimum value of 0, maximum value of 144.
OrderAmountSlider
= new
Scrollbar(Scrollbar.HORIZONTAL,
0, 0, 0, 144);
//
Insert the slider to the Applet panel.
add(OrderAmountSlider);
//
Insert the label which says how many are set to be ordered
//
of the item.
add(AmountLabel);
//
Add the subtotal label and a label saying that it is the subtotal.
add(new
Label("Subtotal: "));
add(SubTotalLabel);
//
Add the total label and a label saying that it is the total.
add(new
Label("Total: "));
add(TotalLabel);
// Insert
a label to signify that this
//
is the personal information (address,etc.)
// section
and also insert text fields to prompt for that information.
add(new
Label("Your information: "));
add(new
Label("Name:"));
add(NameEntryField);
add(new
Label("Street:"));
add(StreetEntryField);
add(new
Label("City:"));
add(CityEntryField);
add(new
Label("Zip:"));
add(ZipEntryField);
//
Add a label to the comment text area.
add(new
Label("Comments:"));
// Add the
comment box.
add(CommentTextArea);
// Method which
resets all of the internal values.
resetValues();
}
// This method will be called when the
user presses the "Clear" button and
// also when the applet is initialized
in the init() method.
public void resetValues() {
// Reset all of
these labels to zero.
SubTotalLabel.setText("$0.0
");
TotalLabel.setText("$0.0
");
AmountLabel.setText("0
");
PricePerItemLabel.setText("$0.0
");
// Clear all of
the lists and choices.
ProductList.select(0);
SizeChoice.select(0);
OrderAmountSlider.setValue(0);
// Clear all of
the text fields.
NameEntryField.setText("");
StreetEntryField.setText("");
CityEntryField.setText("");
ZipEntryField.setText("");
}
// Method which will deal with
some of the events
//generated during execution
// of the applet.
public boolean handleEvent(Event InEvent)
{
// Check to see
if the Slider was changed. If so,
// update the
values in the applet.
if (InEvent.id
== Event.SCROLL_LINE_UP ||
InEvent.id
== Event.SCROLL_LINE_DOWN) {
updateValues();
} else
// If the list
of products was changed then update the applet values.
if (InEvent.target
== ProductList) {
updateValues();
} else
// If the clear
button was pressed, reset all of the applet values.
if (InEvent.target
== ClearButton) {
resetValues();
} else
if (InEvent.target
== QuitButton) {
// Quit the applet.
} else
if (InEvent.target
== SubmitButton) {
// Submit
the order. To be completed later.
}
// Let the parent
handle the event. . .
return super.handleEvent(InEvent);
}
// The rest of the Events will be handled
here. . .
public boolean action (Event InEvent,
Object SomeObject) {
// If the event
was generated by the size choice field
// then update
all of the display.
if (InEvent.target
== SizeChoice) {
updateValues();
// Yes, we handled
the event..
return true;
}
else
// If the event
was generated by the NameEntryField. . .
if (InEvent.target
== NameEntryField) {
/*
Is the field empty? If so, we will later add a pop-up
dialog
box
to alert the user that they have not entered their name.
*/
return true;
} else
// Otherwise,
say that we didn't handle the event. .
return false;
}
/* This void will change all of the values
to match any changes
in the input settings. First,
it declares a number of
variables local to the method. Then,
it sets a modifier
variable and a base price
variable depending on which items
are selected in the choice
box, the list, and the slider.
Then, it inserts those values
onto the applet panel.
*/
private void updateValues() {
// The index of the selected size.
int
WhichChoice = SizeChoice.getSelectedIndex();
// The amount of items desired.
int AmountSelected = OrderAmountSlider.getValue();
// The index of the selected product.
int WhichProduct = ProductList.getSelectedIndex();
/* The initial base price and modifier. Remember,
the modifier is the amount
the base price is
multiplied by to get the
price per item.
*/
double CurrentBasePrice = 0.0;
double CurrentModifier = 0.0;
/* This switch statement compares the
index of the
product list, held in WhichProduct,
and sets the inital BasePrice
accordingly.
*/
switch (WhichProduct) {
case
0:
CurrentBasePrice
= ProdOneBaseValue;
break;
case 1:
CurrentBasePrice
= ProdTwoBaseValue;
break;
case 2:
CurrentBasePrice
= ProdThreeBaseValue;
break;
case 3:
CurrentBasePrice
= ProdFourBaseValue;
break;
}
/* This switch statement compares the
WhichChoice
variable (which is the selected
index in the
sizeChoice choice box) to
the different indexes.
And then sets the modifier
accordingly.
*/
switch (WhichChoice) {
case
3:
CurrentModifier
= multiplierSmall;
break;
case 2:
CurrentModifier
= multiplierMedium;
break;
case 1:
CurrentModifier
= multiplierLarge;
break;
case 0:
CurrentModifier
= multiplierJumbo;
break;
}
// Insert the
number on the slider to the applet.
AmountLabel.setText(Integer.toString(AmountSelected)+
" ");
// Compute the
priceperitem and insert it onto the applet panel.
double PricePerItem
= (CurrentBasePrice*CurrentModifier);
PricePerItemLabel.setText(Double.toString(PricePerItem)+
" ");
// The subtotal
is the number ordered times the price per item.
double SubTotal
= (CurrentBasePrice*CurrentModifier*AmountSelected);
// Insert the
subtotal onto the applet panel.
SubTotalLabel.setText(Double.toString(SubTotal)+
" ");
/* Since the total
is the same as the subtotal
(cause
we only have one item to be ordered
at
a time), we can simply use the value in the subtotal.
*/
TotalLabel.setText(SubTotalLabel.getText());
}
}
Don't you find it interesting how fast these programs grow? If
this information seems unclear, use the comments to follow what's
going on. Here's the general flow of the applet. First, all the
internal variables are declared, and then the Java runtime calls
the init() method. The init()
method allocates many of the variables and defines the layout
of the applet panel. Then the user does something to create an
event. When an event does arise, the handleEvent
and action methods handle
the event. Different methods and actions are taken based on the
event that is generated and on which components are targeted.
For example, when the Clear button is pressed, the clearValues
method is called.
The Order Entry System takes some more great strides in this chapter.
Complete functionality has been added to almost all the components
in the applet. The slider now functions completely, and the value
it sets is now used to compute the correct subtotal and total
based on the choices the user makes. In these ways, the Order
Entry System is doing great. However, there are two major items
wrong with the Order Entry System.
First, you may look at the applet shown in Figure 7.3 and think
something along the lines of "This looks terrible."
Well, you're right. All the pieces to the applet have been added,
but they still haven't been ordered correctly. You do this in
the next chapter when the concepts of containers and layout managers
are covered. The applet looks like a jumbled mess now, but it
improves in the next chapter, "The Order Entry System: Managing
the Applet Layout."
Second, there is still some functionality missing. The applet
should exist as a stand-alone window. The process of implementing
this feature is included in the next chapter. There are also some
instances in which pop-up dialogs should be included in the applet.
For example, if a user does not enter his or her name, a window
should pop up and alert the user that he or she has not entered
information correctly. Stay tuned, more to come.
Data validation, in terms of this book, is the process of checking
data to see if it is correct. As it relates to the Order Entry
System, it is checking text entered through text fields to see
if they are what you want. For example, if you have a field that
accepts a phone number, you should check to see that the text
entered contains 10 integers.
When you want to validate data entered in fields, follow these
steps:
- Write a boolean function
that returns a true or false
when supplied the text from the field. The function returns a
true when the string is acceptable;
false otherwise. To write
this function, parse the string. Java contains a number of useful
functions for parsing strings; they are covered in Chapter 3,
"An Introduction to Java Classes."
- Next, add to your action
method an if statement that
calls the method written in step 1 if the Event.target
is the text field that you are trying to validate. If the result
of the function in step 1 is true,
keep on going. If it is false,
alert the user or do what you want to do.
That's all you have to do. If you noticed, the framework for this
feature is set up in the Order Entry System. After some more topics
are covered in the next chapter, code is enabled such that when
the NameField generates an
event (that is, when the user presses Enter or Return while the
cursor is in the text field) and sends it to the action
method, it calls the CheckName
function, which returns a Boolean. Then, if the CheckName
function returns a false
value, an OK dialog box is set out to alert the user that the
name entry field is empty. If the function returns true,
then you go on your merry way. And that covers it all.
Dealing with Passwords |
While the Order Entry System applet does not use password entry, it is worth covering. When you're prompting someone for a password, it is customary to echo a different character than what is typed. This character is usually an
* or a blank space.
To have a text field echo another character, use the setEchoCharacter method of the TextField class. For example, to set the characters that are echoed to ! when text is typed into a field, you can use the following code line:
ATextField.setEchoChar('!');
You can use a couple more methods in conjunction with the setEchoChar(char) method. The getEchoChar() function returns the echo character. Also, the echoCharIsSet() Boolean function returns whether an echo character is set. It
returns an instance of the boolean variable.
|
In this chapter, you learned about a number of important Java
AWT components. They included all those that deal with the plain
input and output of text. Then you learned how to use these components
by incorporating them into the Order Entry System. I discussed
the Order Entry System and looked ahead to improving it in the
chapters to come. I discussed the process of data validation in
AWT programs and how you could incorporate that into the Order
Entry System.
The next chapter covers some of the most important features of
the AWT. You will learn how to manage the layout of your AWT programs
so that they maintain platform independence while looking good.
You will then apply those techniques to the Order Entry System
as you take more steps to improve it.
Next
Previous
Contents
|