Chapter 6 -- The Order Entry System: Adding
Features and Handling Events
Chapter 6
The Order Entry System: Adding
Features and Handling Events
CONTENTS
This chapter looks into the use and description of the java.AWT
concepts of containers and components. Part of this chapter covers
the implementation of some of the components. The graphical components
of the AWT are covered in this chapter, while others are left
for later chapters. Here is a list of the components that are
covered in this chapter:
Buttons
Checkboxes
Radio buttons
Choice menus
Lists
Scrolling lists
Sliders and scrollbars
Note: |
Notice that the component Canvas is left out of this chapter. It is a graphic component, but for organizational purposes it is included in Chapter 9, "The Order Entry System: Adding Graphics and a Logo."
|
This chapter also covers the implementation of handling user inputs,
or events. This concept is touched on in the preceding
chapter, but to sum it up, events are basically what their name
says, "something happening." Some events are mouse clicks,
keyboard presses, and events created by your own program to "fake"
an event. All these events are covered in the "Handling Events"
section of this chapter.
Finally, this chapter applies the concepts of components, applets,
the AWT, and events to the Order Entry System. In building the
Order Entry System applet, this chapter exercises these features
in the process of coding a larger program. This is the area in
which many instructional books are lacking.
But first, I'll get into some components.
If you remember from the preceding chapter, the component class
is the keystone to the AWT. The vast majority of the available
classes in the AWT derive from this class. This includes the container
class, which is one of the subclasses of the component class.
This is the main reason that you can place components in containers,
and so on. This feature is useful when you manage the layout of
the Order Entry System in Chapter 8, "The
Order Entry System: Managing the Applet Layout," but for
now, just appreciate the power of components and the AWT as a
whole.
Components come in many shapes and sizes. As I stated before,
this chapter covers the components that are graphics-oriented.
Of course, all the components are graphical in nature. They are
drawn just as any other GUI item is, but the components covered
in this chapter are those that are not text-oriented, meaning
not designed for the output or input of text. Placing all the
components in one large section may seem to be the most logical,
but dividing them into two groups keeps you from being bombarded
by 12 explanations at once and also facilitates reference use
of the book. Text-oriented components are covered in Chapter 7,
"The Order Entry System: Entry Fields, Labels, and Validation."
The simplest components are buttons, which are covered next.
In the AWT, buttons are like the buttons found on virtually every
GUI system. Listing 6.1 is an applet that demonstrates the insertion
of buttons in an applet.
Listing 6.1. The heyabutton
applet code.
1.// Import all of the java.awt package
and the applet package.
2. import java.awt.*;
3. import java.applet.*;
4. // Declare the heyabutton class.
5. public class heyabutton extends Applet
6. {
7.
8. // Create a variable aButton
of the Button class.
9. private Button aButton;
10. //
Overriding the default init() method.
11. public void
init()
12. {
13. //
Allocate space for the Button.
14. aButton
= new Button("Longhorn");
15. //
Add the button to the Applet panel.
16. add(aButton);
17.
}
18. }
The heyabutton class, when
viewed from the AppletViewer utility, is shown in Figure 6.1.
Figure 6.1 : The heyabutton applet when viewed from the AppletViewer utility.
Line 1 makes all the classes from the java.awt
package available to you. Line 2 does the same with the applet
package. Line 3 says that this program extends the applet class
in the library. In other words, it is a subclass of the applet
class and shares all functionality of it. You are, of course,
overriding some of the inherited methods with your own declarations.
In this applet, the code in line 6 is doing just that. This line
declares a void that overrides the standard init()
method with your own code.
But before that, line 5 declares a private
button, which means that,
for the purposes of object-oriented design and data encapsulation,
the variable is local to this class and not accessible from outside.
The button type is contained
in the file java.awt.Button.
Line 8 uses the new method,
"make aButton a new
instance of the Button class."
Now, aButton is your very
own instance of the java.awt.Button
class from the library.
So what do you do with it? You have a button; now add the component
to the applet using Java's add()
method. The method add()
is common to all containers that place a component in the container.
(Exactly where it goes is covered with the applet layout in Chapter 8.)
For now, it's enough to know that it puts its parameter in the
container from which it is called. Here's an example:
add(aPanel);
This line adds the aPanel
component to the current container. The following code adds the
aButton component to the
container somecontainer:
somecontainer.add(aButton);
That is the end of the functional part of the applet and the coverage
of buttons and how to add components.
Tip: |
After you have a good bit of Java knowledge, it's a good idea to go into the libraries and check out the contents. If you have experience with object-oriented design programs, such as C++, the library structure should be familiar. If not, Java is a good
language to start with when you are trying to get into object-oriented design.
|
The process of looking at the methods, looking at the data structures,
and going through the implementation does a great deal for your
debugging and code design efforts.
A checkbox is like its name sounds: it's a box you put
a check in. Checkboxes are either on or off, selected or unselected.
The mouse click (or a tab down) on the checkbox toggles its value,
making a checked box unselected and vice versa. You use checkboxes
when you are creating an interface that needs to get data that
is either yes or no. For example, "Would you like to be included
on our mailing list?"
Checkboxes are created using the class java.awt.Checkbox
of the AWT.
Note: |
The line numbers in the following example are for ease of reference only.
|
Here is the standard constructor for creating a checkbox:
1. private Checkbox aCheckbox;
2. aCheckbox = new Checkbox();
Of course, you can combine these two statements:
1. Checkbox aCheckbox = new Checkbox();
Checkboxes, like most classes implemented in Java, are overloaded
to be able to accept different combinations of input. This is
a feature shared with C++ and some other languages designed to
facilitate object-oriented programming.
To create a checkbox and set the label, use the following format:
Checkbox aCheckboxpluslabel = new Checkbox("Label
here!");
To set the checkbox's initial value, you can include another parameter:
Checkbox anotherCheckbox = new Checkbox("Label
here!", null, true);
In this constructor, the first parameter is the label, and the
third parameter is the initial starting value. The second parameter
places the checkbox into a CheckboxGroup.
This is used to create radio buttons, which are a group of checkboxes
in which only one of them can be selected at the same time. Listing
6.2 is an applet that creates and inserts four checkboxes into
an applet.
Listing 6.2. The heysomecheckboxes
applet code.
1. import java.awt.*;
2. import java.applet.*;
3. public class heysomecheckboxes extends Applet
4. {
5. // Override
the initialize method.
6. public void
init()
7. {
8.
// Declare the four checkboxes and set their labels.
9. Checkbox
JonBox = new Checkbox("Jon");
10.
Checkbox IanBox = new Checkbox("Ian");
11.
Checkbox NateBox = new Checkbox("Nate");
12.
Checkbox MichaelBox = new Checkbox("Michael");
13.
// Add the four checkboxes to the applet panel.
14.
add(JonBox);
15.
add(IanBox);
16.
add(NateBox);
17.
add(MichaelBox);
18.
}
19. }
Lines 1 through 6 do the same standard stuff: declare the applet
and import classes, for example. Lines 9 through 12 create four
checkboxes, each with a different label. In this case, four different
names are used. This is helpful if you use an applet (or application)
to report work done on a project and you need to say who has worked
on or contributed to the project. Lines 14 through 16 add these
boxes to the applet. Figure 6.2 shows this applet displayed in
the AppletViewer utility.
Figure 6.2 : The heysomecheckboxes applet when viewed from the AppletViewer utility.
There are four checkboxes with corresponding labels on the applet.
Easy enough, right? Sometimes, though, you may want only one checkbox
in a group of checkboxes to be true at any one time. This situation
is covered in the section on radio buttons.
Here are some of the methods available for controlling instances
of checkboxes:
getState()
| This method is a function that returns the current state of the calling instance of a checkbox. Remember, the state of checkboxes is either true or false.
|
setState(boolean)
| This method allows you to set the state of the calling instance.
|
getLabel()
| This method returns the label of an instance of the checkbox class. The label is of type String.
|
setLabel(string)
| This method allows you to set the label of a checkbox to a new string.
|
The preceding section covered the addition of checkboxes to applets.
The preceding example had the checkboxes operate independently
of each other. But often you want only one checkbox to be true
at a time. This behavior is characteristic of radio buttons in
Java.
There isn't a specific type of RadioButton.
Instead, radio buttons are created by creating a group of checkboxes
and specifying the initial checkbox to be selected. This group
is defined by a class called (surprisingly) CheckboxGroup.
The class CheckboxGroup allows
you to group checkboxes and then manages the states of each checkbox
in the group so that only one is selected at a time. Here is a
sample declaration of a CheckboxGroup:
private CheckboxGroup NameBoxGroup;
NameBoxGroup = new CheckboxGroup();
The process of adding checkboxes to the group is easy. When you
declare a checkbox, you add the group name as another parameter.
For example, you declare a checkbox and want to include it in
the group declared above, NameBoxGroup.
You also want it to be the box that starts with its value as true.
Here is how you do it:
JonBox = new Checkbox("Jon",
NameBoxGroup, true);
Do this for each checkbox you want in the group and you're ready
to go. Listing 6.3 takes the previous example, the heysomecheckboxes
applet, and extends it to include the four names to act as radio
buttons. The new applet is the HeyaCheckBoxGroup
applet.
Listing 6.3. The HeyaCheckBoxGroup
applet code.
1. // import all of the classes in the
java.awt and applet packages
2. import java.awt.*;
3. import java.applet.*;
4. // declare the class HeyaCheckBoxGroup.
5. public class HeyaCheckBoxGroup extends Applet
6. {
7. // Overriding
the standard init() void.
8. public void
init()
9. {
10.
// Declare the NameGroup as a CheckboxGroup().
11.
CheckboxGroup NameGroup = new CheckboxGroup();
12. //
Declare the JonBox as a new Checkbox(), and
do
the same for four more boxes.
//
Also, set the JonBox to be initially true while
the rest are false.
13. Checkbox
JonBox = new Checkbox("Jon",NameGroup,true);
14. Checkbox
IanBox = new Checkbox("Ian",NameGroup,false);
15. Checkbox
NateBox = new Checkbox("Nate",NameGroup,false);
16. Checkbox
MichaelBox = new Checkbox("Michael",NameGroup,false);
17.
18. //
Add all of the Checkboxes to the applet panel.
19. add(JonBox);
20. add(IanBox);
21. add(NateBox);
22. add(MichaelBox);
23.
}
24. }
This applet declares an instance of CheckboxGroup
in line 10. Lines 13 through 16 declare four checkboxes and insert
them into the NameGroup with
the JonBox being set initially
true. Then the four boxes
are added to the applet using the add
method in lines 19 through 22. Figure 6.3 shows this applet.
Figure 6.3 : The HeyaCheckBoxGroup applet when viewed from the AppletViewer utility.
Other methods are available in checkboxes that deal with checkbox
groups:
getCheckboxGroup()
| This allows you to get the group to which a checkbox belongs.
|
setCheckboxGroup(CheckboxGroup cbg)
| This allows you to change the group to which a checkbox belongs. It takes an instance of CheckboxGroup as a parameter.
|
Also, the setCurrent(Checkbox)
and getCurrent() methods
of the CheckboxGroup class
allow you to set and get the currently chosen checkbox.
Pop-up choice lists allow you to combine many different choices
into one area. A large number of radio buttons can become unwieldy,
so this type of choice list puts many different choices into one
compact area. Figure 6.4 is an applet that features a pop-up choice
list viewed from the AppletViewer utility:
Figure 6.4 : A choice list.
Choice boxes come from the java.awt.Choice
class. To declare a new choice box, you can use the following
code:
Choice names = new Choice();
To insert items into the list, you use the addItem()
method of the Choice class.
The addItem() method takes
a string as a parameter. Here is the code to place the four names-Jon,
Ian, Nate, and Hal-into the choice list called names:
names.addItem("Jon");
names.addItem("Ian");
names.addItem("Nate");
names.addItem("Hal");
The items are listed in the pop-up choice list in the order in
which they are added. The selection in the box is the current
selection of the choice list. To change it, use the method select().
It is overloaded to accept both integers and strings. Should you
want to select the third choice in a list initially, use the code:
names.select(3);
To choose the string "Jon",
you use the following:
names.select("Jon");
The getItem() method allows
you to get the string at a certain position if you know the index.
Simply give it an integer, and it returns the string at that position.
Also, after you put an item in the list, it is there for good;
there is no way to get it out.
On some occasions, you want to have all the selections available
for viewing at one time. You can do so by using scrolling lists.
They allow more than one item to be selected at a time. Figure
6.5 shows an applet that contains a scrolling list.
Figure 6.5 : A scrolling choice list.
Lists are declared using the following constructors:
List()
| This is the default constructor. Only one choice may be selected at a time.
|
List(int, boolean)
| This creates a scrolling list of the size defined in the integer parameter, and the Boolean flag sets the ability to have multiple selections. True means that it can have multiple selections; false means it
can't.
|
Here is an example construction of a list that specifies six items
able to be viewed at one time and allows multiple selections at
one time:
List Names = new List(6, true);
As with pop-up choice lists, you use the addItem()
method of lists to insert items into the list:
Names.addItem("Hal");
Names.addItem("Nate");
Names.addItem("Evan");
Another instance of the addItem
method allows you to set where you want the next item inserted
in the list. Here is an example that places another name at position
four in the list:
Names.addItem("Ignacio",4);
You can also use the select()
method to set which items you want initially selected. The following
two lines set the first and fourth items in the list to be highlighted:
Names.select(1);
Names.select(4);
Figure 6.6 shows the preceding declaration, plus a few more, added
into an applet viewed through the AppletViewer utility.
Figure 6.6 : The ScrollListExample applet viewed through the AppletViewer utility.
Listing 6.4 shows the ScrollListExample
applet code.
Listing 6.4. The ScrollListExample
applet code.
1. // import all of the classes in the
java.awt and applet packages
2. import java.awt.*;
3. import java.applet.*;
4. // declare the class HeyaCheckBoxGroup.
5. public class ScrollListExample extends Applet
6. {
7. // Overriding
the standard init() void.
8. public void
init()
9. {
10.
List Names = new List(6,true);
11.
12. Names.addItem("Hal");
13. Names.addItem("Nate");
14. Names.addItem("Ignacio,4");
15. Names.addItem("Yi");
16. Names.addItem("Wilson");
17. Names.addItem("Robb");
18. Names.select(1);
19. Names.select(4);
20. add(Names);
21.
}
22.}
A number of other useful methods are available in the List()
class:
clear()
| This removes all the items from the list. |
getItem(integer)
| This returns the string at the index specified by the parameter.
|
countItems()
| This returns an integer specifying the number of items currently in the list.
|
replaceItem(string, integer)
| This replaces the item at the index specified by the integer with the string.
|
getSelectedIndex()
| This returns an integer specifying the position in a list of the selected item.
|
getSelectedIndexes()
| This returns an array of integers, each of which specify the indexes of all the selected items.
|
getSelectedItems()
| This returns an array of strings that are all the selected items at the current time.
|
getSelectedItem()
| This returns the string that is currently selected.
|
Scrollbars are common to every graphical user interface system.
In the AWT, they are used to scroll areas such as lists and sliders,
which are a graphical means to set values. Figure 6.7 shows a
small applet that includes a slider.
Figure 6.7 : An applet with a slider.
As sliders, scrollbars are used to input a value to the program
from the user. The programmer can set the initial minimum value,
the maximum value, the orientation, and the visible area of the
scrollbar. You also can set how the scrollbar changes per different
user actions. This activity is described later in this chapter
when the process of handling events in the AWT is covered.
This section covers the construction of instances of the Scroll()
type and their implementation. Chapter 8
covers using scrollbars to scroll through a window. There are
two major ways to construct a scrollbar.
Scrollbar(int) constructs
a scrollbar and sets the initial orientation (vertical or horizontal)
of the scrollbar. The int
you send in is either Scrollbar.HORIZONTAL
or Scrollbar.VERTICAL. These
are the only values currently available to you. You can then later
use the setValues(int initial,
int visiblearea, int min, int max)
method to set the initial value, the visible area of the window,
the minimum value, and the maximum value for the scrollbar, respectively.
Scrollbar(int orientation, int
visiblearea, int initial, int min, int max),
takes five parameters (in this order): the orientation (either
Scrollbar.HORIZONTAL or Scrollbar.VERTICAL),
the visible area value, the initial value, the minimum value,
and the maximum value.
The page value is the amount that the value of the scrollbar changes
when a user clicks on the area between the end arrow and the current
position. To set the page increment value, use the setPageIncrement(int
pageincrement) method, which takes an integer
parameter and makes that value the page value.
The line increment is the amount that the scrollbar changes when
a user clicks on the end arrow of the scrollbar. The method to
change or set this value is the setLineIncrement(int
lineincrement) method of the Scrollbar
class. As with the setPageIncrement(int
pageincrement) method, this method accepts an
integer.
Listing 6.5 is a sample applet that contains two scrollbars, using
both of the Scrollbar() constructors
discussed previously.
Listing 6.5. The TwoScrollBars
applet code.
1. import java.awt.*;
2.
3. public class TwoScrollBars extends java.applet.Applet
4. {
5. public void
init()
6. {
7. // Declare
the Vertical Bar as a horizontal scrollbar.
8. Scrollbar
VertBar = new Scrollbar(Scrollbar.VERTICAL);
9. // Set
the values to be: initial value 25,
10. visible,
area to 35, min to 0, max to 200.
11. VertBar.setValues(25,
25, 0, 200);
12. //
Add the scrollbar to the applet panel.
13. add(VertBar);
14.
15. //
Declare the HorizBar as a horizontal scroll bar,
16.
with initial 16. value 10, visible area of 50,
17. //minimum
of 0, and maximium of 200.
18. Scrollbar
HorizBar = new Scrollbar
19. (ScrollBar.HORIZONTAL,
10, 50, 0, 200);
20. // Add
the HorizBar to the applet panel.
21. add(HorizBar);
22.
}
23.}
Lines 1 through 6 do the standard stuff: declare the applet and
import classes. Line 8 declares the scrollbar and sets the initial
orientation of the VertBar
variable. Then the setValue()
method is used to set the initial value, the visible area, the
minimum value, and the maximum value. The scrollbar is then added
to the applet panel. In lines 15 through 21, basically the same
thing happens, except that all the setup done in setting and adding
the HorizBar is done in lines 18, 19, and 21.
Note: |
There are actually more constructors for creating scrollbars. However, in the end, they all produce the same product and are just as easy. By providing you with the "all in one" constructor that takes five parameters, and also including a
minimalist constructor that takes only one parameter, I hope that you are getting a feel for the whole range of constructors.
|
Here is a summary of the Scrollbar
methods and declarations:
Scrollbar(int orientation, int visiblearea,
int initial, int min, int max) The
parameters set the orientation, visible area, initial value, minimum
value, and maximum value respectively.
setPageIncrement(int) As
discussed previously, this sets the page increment. This is the
amount that the scrollbar changes when the user clicks between
the current position and the endpoint.
setLineIncrement(int) As
discussed above, this sets the line increment. The line increment
is the amount that the scrollbar changes when the user clicks
on the end arrow of the scrollbar.
setValues(int initial, int visible
area, int min, int max) This
is the method to set the initial value, the visible area of the
window, the minimum value, and the maximum value for the scrollbar
respectively.
int getValue() This
returns the current value, an integer, of the scrollbar. This
is the main method used later when making scrollbars active.
In any of the examples discussed in this chapter, you may notice
that something is wrong. The insertion and setup of these different
components of the AWT are covered except how to handle them when
something happens with them. For example, nothing happens when
you click on the buttons that have been created. Handling user
actions like button selection is covered later in this chapter.
But first, let's get started on creating the Order Entry System.
This section covers how to create and insert the different components
to be used onto the applet panel. Don't worry about the positioning
of the buttons. This is taken care of when you manage the applet
layout in Chapter 8. For now, just worry
about creating the components and slapping them down.
Also, notice that the Order Entry System exists as a stand-alone
window. This also is covered in Chapter 8.
Finally, the logo is left out for now because it is covered in
Chapter 9.
Ideally, you want to use every component to give yourself a feel
for them. So give it a shot, even though it may complicate matters.
For the time being, you are going to implement the components
covered in this chapter.
To start off, import all the AWT classes and also the Applet package
as follows:
import java.awt.*;
import java.applet.*;
And then declare the applet class like this:
public class OrderEntrySystem extends
Applet {
The customary place to initialize and set up your applet is in
the init() method. So, declare
the init() method and insert
and declare your first component, a button that reads Submit.
Here is the code segment that declares the button and inserts
it onto the applet panel:
Button SubmitButton = new Button("Submit");
add(SubmitButton);
Continue doing the same tasks for two more buttons labeled Quit
and Clear, in the same manner.
Next, insert a checkbox that asks if the person using the system
is a repeat customer:
Checkbox RepeatCustCheckBox = new Checkbox("Repeat
Customer?");
add(RepeatCustCheckBox);
You also should query the users as to how they are to be contacted.
The choices are phone, e-mail, or U.S. mail. A radio button setup
is ideal for this query since you want only one button to be active
at one time. The first step in creating radio buttons is to create
an instance of the CheckboxGroup
class that coordinates the behavior of all the instances of the
Checkbox class. Add the following:
private CheckboxGroup ContactMethodGroup;
ContactMethodGroup = new ContactMethodGroup();
Next, create the buttons you're going to put in the group, using
the declaration method specified previously:
Checkbox EmailBox = new Checkbox("Email",ContactMethodGroup,true);
Checkbox PhoneBox = new Checkbox("Phone",ContactMethodGroup,false);
And so on for the rest of the buttons. Because you'd rather e-mail,
set the Email button to be
initially true while the rest are false. Also, remember to add()
all the buttons. There are a number of products to choose from
in the applet, so set a means to choose from a number of products.
Chapter 11, "Reading and Writing
with Java," touches on how you could read in a file that
contains all the products and prices. For now, set all the products
in the program. First, construct the ProductList
class as an instance of the List
class and add some of the products.
List ProductList = new List(4, false);
ProductList.addItem("Oscar");
ProductList.addItem("Lionhead");
ProductList.addItem("Jack Dempsey");
ProductList.addItem("Angelfish");
.
.
The first parameter sets the list to have four items visible at
a time. The second sets the list so that only one item may be
selected at a time. There's also a pop-up choice box to let the
user select the size of the product (in this case, fish) that
he or she wants. To declare a choice box, you use much the same
code as above.
Finally, the last component to add is a slider. This is used to
allow the user to input the amount of each product that he or
she wants to order. Here is the declaration for the slider:
Scrollbar OrderAmountSlider = new Scrollbar(Scrollbar.VERTICAL,
0, 0, 0, 100);
add(OrderAmountSlider);
The scrollbar is declared to be vertically oriented, with a visible
area of zero, an initial value of zero, a minimum of zero, and
a maximum of 100.
Listing 6.6 is the complete code listing, showing what you should
have so far in building the Order Entry System.
Listing 6.6. The OrderEntrySystem
applet code so far.
import java.awt.*;
import java.applet.*;
public class OrderEntrySystem extends Applet {
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);
//
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);
//
Create the list, 4 items visible, no multiple
//
selections.
List
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);
//
Create the Choice box.
Choice
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);
//
Create a vertical slider, initial value of 0,
//
minimum value of 0, maximum value of 144.
Scrollbar
OrderAmountSlider = new
Scrollbar(Scrollbar.VERTICAL,
0, 0, 0, 100);
//
Insert the slider to the Applet panel.
add(OrderAmountSlider);
}
}
Figure 6.8 shows what you see when you view
this applet through the AppletViewer utility.
Figure 6.8 : The start of the Order Entry System applet.
If you run the Order Entry System applet so far, you will notice
something a little peculiar: nothing happens. You can click on
the buttons, move the slider, and whatever else, and nothing happens.
These user actions are called events in the Abstract Windowing
Toolkit. Your program has to be able to deal with these events
and give the proper response. For example, if a user clicks the
up arrow on a slider, your program has to react and increment
a variable. If a Clear button
is clicked, your program has to reset all the data that has been
input to default values. The next section covers the implementation
and concepts behind events and handling them. It also deals with
the specialized action()
method used for different types of component events. And after
that, it sets up much of the dealing with events in the Order
Entry System. Also, you may think, "It looks terrible."
Well, you're right. Hold on because the solutions are coming up
in future chapters.
Some events in the AWT are mouse drags, window resizing, and slider.
Your programs that use the AWT are set to react to each event.
This makes programs based on the AWT very different from typical
programs. When you're creating a windowing system, one of the
tasks you do is enable your system to act on an event-by-event
basis as opposed to a linear basis. The AWT takes this responsibility
out of your hands.
Events in Java are declared using the Event
class. Different types of events are identified by a different
constant held in Event.id.
Each different type of event, such as mouse clicks and window
resizing, is identified by a different constant. For example,
if a mouse button is pressed, an event is generated whose id
is equal to the constant MOUSE_DOWN.
Table 6.1 explains all the mouse and keyboard event types. Table
6.2 contains events related to windows. Table 6.3 contains the
miscellaneous events such as the event ids
specific to the List class
and scrolling events, and Table 6.4 lists the different values
contained in instances of the Event
class.
Table 6.1. The keyboard and mouse event id types.
ID Constant | Meaning
|
KEY_PRESS
| Generated when a key is pressed. |
KEY_RELEASE
| Generated when a key is released. |
MOUSE_UP
| Mouse button is released. |
MOUSE_DOWN
| Mouse button is pressed. |
MOUSE_ENTER
| Mouse enters the window area. |
MOUSE_EXIT
| Mouse exits the window area. |
MOUSE_MOVED
| Mouse is moved. |
MOUSE_DRAG
| Mouse is dragging something. |
HOME, PGDN, PGUP, etc.
| Action key is pressed. |
f1 . . f12
| The function keys. |
LEFT, UP, RIGHT, etc.
| Arrow key pressed. |
ACTION_EVENT
| An action event occurs. |
Table 6.2. The event id types for window events.
ID Constant | Meaning
|
WINDOW_DESTROY
| Destroy button pressed on window. |
WINDOW_ICONIFY
| Window told to minimize. |
WINDOW_EXPOSE
| Window told to "expose" itself. |
WINDOW_MOVED
| Window moved. |
Table 6.3. Miscellaneous event types.
ID Constant | Meaning
|
SCROLL_LINE_UP,
| The different scroll events for different user inputs
|
SCROLL_PAGE_DOWN, and so on
| on scrollbars. |
SCROLL_ABSOLUTE
| Scrollbar is moved. |
LIST_SELECT, LIST_DESELECT
| An item in the list selected or deselected.
|
LOAD_FILE, SAVE_FILE
| A saving file event, for example. |
GOT_FOCUS, LOST_FOCUS
| A component gets or loses the focus. |
Table 6.4. The different values contained in instances
of the Event class.
Name | What It Is
|
Object target
| Which component generates the event. |
long when
| A time stamp. |
int id
| A constant that says what kind of event it is.
|
int x |
The x coordinate of the event. |
int y |
The y coordinate of the event. |
int key
| The key that is pressed. |
int modifiers
| Which modifier key is used (ALT, for example).
|
clickCount
| The number of consecutive click counts (2 for a double-click, 0 if it isn't set, for example).
|
Object arg
| An arbitrary argument used for customization.
|
Note: |
A few more event constants than these are available. However, the event.ids covered in this chapter are effective for almost all purposes.
Also, the when member of the Event class is used for time stamping. You generally don't worry about this because the vast majority of programs you deal with are event-driven and not linear.
|
After an event occurs, the Java runtime constructs an instance
of the Event class and sets
its id field appropriately.
It then sends that instance to the handleEvent()
method of your Java program that overrides the default handleEvent()
method. This method deals with the event appropriately.
The handleEvent() method
is a Boolean function. Three possible results can be returned:
true, false,
or super.handleEvent(Event).
A returned true value signifies
that your handleEvent() method
has taken care of the event. A false
value signifies that your event has not been handled. This is
not desirable. The proper path for events to be handled is first
through a class and then through its parent. A false
value has the event sent to the parent container, and you don't
want that. Instead, return super.handleEvent(Event),
which sends the event to a parent of a class (the class it has
been derived from) to be dealt with. To summarize, either return
true, saying that your handleEvent()
took care of the event, or return super.handleEvent(Event)
to show that you didn't handle the event and your parent class
should.
Notice that some events are missing in the previous lists. What
about events resulting from instances of the Choice
class? Well, these kinds of events are more easily handled with
a Java method called the action()
method. With the action()
method, events work a little differently. The
action() method deals with
events that are generated by the AWT components themselves. The
different components all create specific action events that your
AWT programs can override to deal with specific events. The action
method has the following structure:
public boolean action(Event InEvent,
Object SomeObject) {
if (InEvent.target == AButton) {
. . .
} return . .
}
The action void
returns, like the handleEvent()
method, either true or false
depending on whether the method has handled the event. Each different
component calls the action
method in a different way, using different parameter values in
place of the SomeObject parameter.
The InEvent parameter in
the event is the calling component, and the SomeObject
parameter can be anything (because basically everything in Java
derives from an Object).
When the action method is
called for button presses, the argument is the string label of
the button. When it is called from an instance of the Choice
class, the argument is the selected string.
There are also specialized methods that handle very specific events.
You can use them to simplify your other event-handling methods.
Table 6.5 is a summary of these specialized event-handling methods.
Table 6.5. The different types of action and related
methods.
Method | When Called
|
action(Event InEvent, Object SomeObject)
| The standard action method. |
keyUp(Event InEvent, int key)
| Mouse button is released. |
keyDown(Event InEvent, int key)
| Mouse button is pressed. |
mouseUp(Event InEvent, int xpos, int ypos)
| Mouse button is released. |
mouseDown(Event InEvent, int xpos, int ypos)
| Mouse button is pressed. |
mouseMove(Event InEvent, int xpos, int ypos)
| Mouse is moved. |
mouseDrag(Event InEvent, int xpos, int ypos)
| Mouse is dragging. |
mouseEnter(Event InEvent, int xpos, int ypos)
| Mouse has entered the component. |
mouseExit(Event InEvent, int xpos, int ypos)
| Mouse has left a component. |
In summary, user actions in Java can be categorized into those
that are handled by the handleEvent()
method and those that are handled by the different types of action
methods. There is a large amount of overlap. It is easy to use
the handleEvent method to
deal with many of the component events covered by the action
method. To do this, test for the ACTION_EVENT
event id and then act based
on the value of Event.target.
However, using both the more specific action
methods and the handleEvent
method ensures that your code is easier to read, design, and maintain.
Of course, as with many languages, Java allows you many ways to
do things, and with experience you will develop your own style.
Listing 6.7 is a sample applet that deals with handling events
using both the action method
and the handleEvent method.
Tip: |
Cases and syntax are very important in Java, especially when you're dealing with overriding methods and inheritance. For example, if you declare a HandleEvent() method and execute your Java program expecting it to override the
handleEvent() method in the AWT, nothing happens. When in doubt, look for these kinds of errors.
|
Listing 6.7. The Event applet code listing.
1. import java.awt.*;
2. import java.applet.Applet;
3.
4. public class EventExample extends Applet {
5.
6. // Declare a local variable, AList of
the List type.
7. private List AList;
8. // Declare a local variable, AButton
of the Button type.
9. private Button AButton;
10.
11. // Override the default init() method.
12. public void init() {
13. /*
Allocate space for the AList. Set it to show four
14.
items visible at one time and turn off the ability
15.
for the user to make multiple selections with the
16.
false boolean parameter. */
17. AList
= new List(3, false);
18.
19. //
Add four items to the List class and initially select item #1..
20. AList.addItem("Blue");
21. AList.addItem("Yellow");
22. AList.addItem("Green");
23. AList.addItem("Red");
24. AList.addItem("Purple");
25. AList.addItem("Orange");
26. AList.select(1);
27. //
Add the list class to the applet panel.
28. add(AList);
29.
30. //
Allocate space for the AButton.
31. AButton
= new Button("Click Me");
32.
33. //
Add the button to the applet panel.
34. add(AButton);
35.
36. }
37.
38. /* Overriding the default HandleEvent
method. Here we will
39. write code to receive
Events from the Java run time. */
40. public boolean handleEvent(Event
inEvent) {
41.
42. /*
Check to see what kind of Event we're given, if
43.
it is an Event where the user selects an item in
44.
our list, then we're going to deselect that item
45.
and reselect number 1. */
46. if
(inEvent.target == AList)
47. {
48. if
(inEvent.id == Event.LIST_SELECT)
49. {
50. /*
Make the first item in the list the
51. selected
item. */
52. AList.select(0);
53. }
54. }
55. return
super.handleEvent(inEvent);
56. }
57.
58. public boolean action(Event InEvent,
Object SomeObject) {
59. if
(InEvent.target == AButton)
60. {
61. //
Set the label equal to the selected list item.
62. AButton.setLabel(AList.getSelectedItem());
63. return
true;
64. }
else
65. return
false;
66. }
67. }
Figure 6.9 : Screen shot of the EventExample applet.
If you try out this applet, you'll notice that it is a little
frustrating. No matter what you choose, it always selects back
to Blue. This is accomplished
by the handleEvent() method
declared starting in line 34. The method only checks the Event
to see if its id is equal
to that of having something selected in a list, LIST_SELECT.
If it is, line 52 sets the selected member of the list to item
number 0. Eventually, Java comes back and repaints the applet
window and the list component itself.
Then line 55 tells the default method to handle the event. This
way, it still does tasks like window resizing in stand-alone windows
and customizes your own handleEvent()
without having to cover all the rudimentary and mundane tasks.
Line 58 is the place where the action
method is declared. It is used for a couple of reasons. One, it
is an aspect of Java you should know about. Two, it is much easier
to use the action method
instead of the handleEvent()
method to handle events from components like choices. In any case,
line 59 checks to see if the Event
is generated by the AChoice
choice, and if it is, sets the button label to the currently selected
item in the list. As is customary, the action
method returns a true if
it handled the event; it returns false
if it did not.
Note: |
The Shift, Alt, Ctrl, and Meta keys are all supported by Java. For example, if you are testing for the Alt+PgDn combination being pressed, the code is the following:
public boolean handleEvent(Event InEvent)
{
if (InEvent.id == Event.KEY_PRESS)
{
if (InEvent.key == Event.PGDN) &&
(Event.ALT_MASK & InEvent.modifiers) != 0)
{
// Do what you wanna do.
}
}
}
The only thing new here is dealing with the most interior if statement. This statement checks to see if the key pressed is PgDn and also to see if the modifier contained in the event signifies the Alt key.
|
The following are basically all the general guidelines to follow
when creating an AWT-based program that is event driven.
First, figure out what you want. If you want buttons, declare
them. In your applet (preferably in your init()
method, although it doesn't have to be there), set up the panel
layout. Add your components, and as covered in Chapter 8,
manage the applet layout.
Second, design your method to handle the events you receive. In
the handleEvent (along with
the action method if you
want), test the Event.id
to see what kind of event you are given. For each id
type you want to recognize, check it against the constants such
as MOUSE_DOWN and react accordingly.
For instance, if the Event.id
equals KEY_PRESSED, then
you want to check your instance of Event.key
to see which key has been pressed.
Third, set the handleEvent()
method to return the proper value: true
if you have handled the event properly or super.handleEvent(Event)
if you want the applet's immediate parent to handle the event.
You need to set up the framework to handle events in the Order
Entry System. To do this, write the handleEvent()
method and add it to the applet that you have developed so far.
Also, add some of the variables that are local to the applet.
First, you handle the events of the Clear button being pressed,
as follows:
if (InEvent.target == clearButton)
{
// Reset all of the variables
and settings .
.
.
}
Do the same for each of the other buttons, and put the respective
code for their functions in as you go along. You aren't able to
code the Send button's function completely until later in the
book.
You don't need to do anything to make the Repeat Customer? checkbox
active. When the data is collected and sent under the Send button's
actions, the checkbox value is checked and sent. You can also
accomplish this with the radio button group, checking each checkbox
when the send-off time comes.
You may have noticed in the figures of the Order Entry System
in Chapter 5, "Writing a Java Applet:
The Order Entry System," that the applet keeps a running
total and subtotal of the items currently selected to be ordered.
You need to declare some internal variables: one for each subtotal
being calculated and one for the grand total. Here are the declarations
for these variables:
private double SubTotalOne = 0,0;
private double Total = 0.0;
For now, you are going to enter only one product and the size
for that product. Each product has a base price and a price modifier
depending on the size. The subtotal is calculated by multiplying
the base price, the number of items desired, and the price modifier
together. The total is calculated as the sum of all the subtotals.
Here are the local variables used for computing price:
private double multiplierSmall = 0.5;
private double multiplierMedium = 1.0;
private double multiplierLarge = 1.5;
For now, hardwire the prices and the different products into the
applet. Later in Chapter 14, "Extending
Java," you learn techniques to read files from your server
and then use the data in your applets. The following constants
are the base prices for each product:
static double ProdOneBaseValue = 1.0;
static double ProdTwoBaseValue = 1.33;
static double ProdThreeBaseValue = 1.75;
static double ProdFourBaseValue = 8.75;
static double ProdFiveBaseValue = 0.33;
You have to override the action
method in the applet to handle most of the events coming from
the components. You don't need to deal with the radio buttons
and the checkboxes in the applet because their immediate values
don't have an effect on the function of the component. The action
method handles the events generated by the choice box. Here is
the code section from inside the action
method that modifies the subtotal and total variables when a new
product choice is made:
public boolean action (Event InEvent,
Object SomeObject) {
.
.
if (InEvent.target == SizeChoice) {
updateValues();
}
.
.
The updateValues() function
is a void that is declared
locally to update all the totals. It is implemented later in the
book.
This is all that is taken care of in the action
method as opposed to the handleEvent()
method, which covers everything. You still have to update the
totals and the multipliers when the list selection (for example,
what the size chosen is) is made. To do this, add some code to
the handleEvent() method
to call the updateValues()
function when a new list selection is made. It is handled in the
same way as the list has been handled in the previous EventExample.
Finally, you need to updateValues()
when the slider is changed. The code to do this is placed in the
handleEvent() method. Here,
you are checking to see if the current event is one of either
line up or line down (for example, someone presses the end arrow).
public boolean handleEvent(Event InEvent)
{
.
.
if (InEvent.id == Event.SCROLL_LINE_UP ||
InEvent.id == Event.SCROLL_LINE_DOWN)
{
updateValues();
}
And that covers the events in everything that's been added so
far. Listing 6.8 is this chapter's final version of the Order
Entry System applet.
Listing 6.8. The Order Entry System code listing.
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;
// 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;
static double ProfFiveBaseValue = 0.33;
// 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;
// Initialize the Applet.
public void init()
{
//
Add and create three buttons.
SubmitButton = new Button("Submit");
add(SubmitButton);
ClearButton
= new Button("Clear");
add(ClearButton);
QuitButton
= new Button("Quit");
add(QuitButton);
//
Add and create the repeat customer checkbox.
RepeatCustCheckBox
= new Checkbox("Repeat Customer?");
add(RepeatCustCheckBox);
//
Declare the CheckboxGroup, and allocate space.
CheckboxGroup
ContactMethodGroup;
ContactMethodGroup
= new CheckboxGroup();
//
Create some checkboxes to put in the group.
EmailBox
= new Checkbox("Email",ContactMethodGroup,true);
PhoneBox
= new Checkbox("Phone",ContactMethodGroup,false);
MailBox
= new Checkbox("US Mail",ContactMethodGroup,false);
//
Add the checkboxes into the applet panel.
add(EmailBox);
add(PhoneBox);
add(MailBox);
//
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);
//
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);
//
Create a vertical slider, initial value of 0,
//
minimum value of 0, maximum value of 144.
OrderAmountSlider
= new Scrollbar(Scrollbar.VERTICAL, 0, 0, 0, 100);
//
Insert the slider to the Applet panel.
add(OrderAmountSlider);
}
public boolean handleEvent(Event InEvent)
{
if (InEvent.id
== Event.SCROLL_LINE_UP ||
InEvent.id
== Event.SCROLL_LINE_DOWN) {
updateValues();
} else
if (InEvent.target
== ClearButton) {
// Reset all of the variables and settings .
} else
if (InEvent.target
== QuitButton) {
// Quit the applet.
} else
if (InEvent.target
== SubmitButton) {
// Submit
the order.
}
return super.handleEvent(InEvent);
}
public boolean action (Event InEvent,
Object SomeObject) {
if (InEvent.target
== SizeChoice) {
updateValues();
return true;
} else return
false;
}
private void updateValues() {
// Empty for now.
}
}
You've made great steps forward with the Order Entry System in
this chapter. You started with nothing, and now it has an initial
layout along with a framework for functionality. There is, however,
still a good amount wrong with the applet. First, the totals,
subtotals, and scrollbar values are not placed on the applet panel.
You fix this in the next chapter, where the AWT components that
deal with text input and output are covered. How to place text
on the applet to better organize it is also covered in the next
chapter. Finally, where's the text input? It is coming in the
next chapter, "The Order Entry System: Entry Fields, Labels,
and Validation."
Next
Previous
Contents
|