AN EXAMPLE WINDOWING APPLET



In this example, we are going to create a simple interactive window as an applet. We will illustrate the topics of windowing and event handling that were mentioned in the previous section.

This applet will display two text fields, with labels "Output: " and "Input: ", and a button, labelled "DISPLAY MOM". If the user presses the button, the "Output: " text field will display the message "Hi, Mom!". If the user types text in the "Input: " text field and hits the enter key, that text will be displayed in the "Output: " text field and will be erased from the "Input: " text field.

The Applet

The applet is shown below. You can experiment with it to see how it works. (You must first click in the input text field in order to enter text.)
With a Java-compatible browser this would display a GUI for interaction.

We can implement this window as a Java applet by

  1. Defining the widgets.
  2. Writing code to create the widgets when the applet is initialized.
  3. Writing code for the actions to be performed when the button is clicked on or when text is entered into the text fields.

Defining the Widgets

The widgets used in this window are :

Discussion of the Code

Click on source to view the entire source code.

The First Few Lines


import java.awt.*;

This statement imports the AWT library (package) to do the windowing in Java.

The Class Definition and the Instance Variables


1: public class window_ex extends java.applet.Applet {
2:
3:    // Instance variables
4:
5:    TextField input_text, output_text;  // Textfields
6:    Button display_button;               // Display button
7:    Label input_label, output_label;    // Labels for textfields

Line 1 defines a public class called window_ex that extends (inherits from) java.applet.Applet. (Thus an instance of class window_ex is an applet.) Java requires that the class be public. The next lines are instance variables for the window_ex class. Line 5 specifies the TextField variables to be used for the text widgets. Line 6 specifies the Button variable that will be pressed to display the message "Hi, Mom!". Finally, line 7 defines the Label variables to be used to identify the text windows in the applet.

init() Method

When an applet is first started, its init() method is invoked before any other method (except its constructor). The init() method performs setup and initialization functions that you might expect to be done in a constructor method. However, for graphical objects such as windows and applets a constructor method normally does nothing, and any needed setup and initialization are done in the init() method.

An init() method is inherited by all descendents of the Component class (including applets), but the inherited method does nothing useful so we override it with our own. In our init() method, we will want to set the background and foreground colors, display the "DISPLAY MOM" button, and display the two text fields.

First, we are going to set the background to blue and the foreground (the drawing color) to white. Then, we will set up a layout manager, which handles how the widgets are going to be displayed and where they are going to be displayed. Next, we will create a button, create the labels, and create the two text fields. Finally, we will add these widgets to the layout manager to be displayed.

Let's look at the source code for the init() method:


1:     // Overridden init() method
2:     public void init () {
3:     // Initialize the window.
4:         setBackground(Color.blue); // Set background color to blue.
5:         setForeground(Color.white); // Set foreground color to white.
6: 
7:         setLayout(new FlowLayout()); // Set flow style.
8:  
9:         // Create the display button.
10:           display_button = new Button("DISPLAY MOM");
11:           add (display_button);
12: 
13:        // Create input label and text field.
14:           input_label = new Label("Input: ");
15:           input_text = new TextField(15);
16:           add(input_label);
17:           add(input_text);
18: 
19: 
20:        // Create output label and text field.
21:           output_label = new Label("Output: ");
22:           add(output_label);
23:           output_text = new TextField(15);
24:           add(output_text);
25:           output_text.setEditable(false); // Make output field not editable.
26:       
27:        
28:    }

Lines 4 and 5 set the background color to blue and the foreground color to white by using the setBackground() method and the setForeground() method, respectively. Line 7 sets up the layout style of the widgets as a flow layout. A flow layout manager simply adds the components to the applet column by column. If the widgets get to the edge of the applet, then they are wrapped around to the next line. Further information on the flow layout manager and the other layout managers can be found at the Java documentation site.

Line 10 creates display_button as a Button object with the label "DISPLAY MOM" (but does not display it). Line 11 causes the button to be displayed by using the add() method to send the button to the layout manager for display.

Line 14 will create a label with text "Input: " to identify the input text field on the applet. The next line, input_text = new TextField(15);, creates a text field of length 15 for the input text. To display the items (the label and the text field), the add() method is used in lines 16 and 17 to send the label and text field items to the layout manager to display. Next, the output_text text field and its label are created and displayed in the same manner. Finally, line 25 sets the output_text text field to be not editable, which means the user cannot type any text into it, by using the setEditable() method.

action() Method

The action() method must be declared public and must return a boolean value as to whether or not an action was completed for the event. In Java's AWT, as in most windowing systems, whenever a button is pressed, or whenever a mouse is moved, or whenever another type of event requiring program action occurs in a window, there needs to be an action defined for the event.

Event handling is discussed in further detail later in the Handling Events section.


1:         public boolean action (Event evt, Object arg) {
2:         // Handle the actions of the window.
3:               // Button hit
4:                  if (evt.target instanceof Button) {
5:                     DisplayText(evt);
6:                     return true;
7:                 }
8:             // Text field data entry
9:                 else if (evt.target instanceof TextField) {
10:                        if (evt.target == input_text) {
11:                           out_string = input_text.getText();
12:                           DisplayEnteredText();
13:                           input_text.setText("");
14:                        }
15:                }
16:                return false;
17:         }

Look at Line 1. Here we declare a public action() method that overrides the default action() method. Line 4 tests to see that if the target of the event was an instance of the Button class. Line 5 invokes the DisplayText() method, which is a (non-inherited) method of our window_ex class (shown later) that displays the text "Hi, Mom!".

Line 11, out_string = input_text.getText(), gets the text entered by the user in the input_text text field. (A text field event occurs when the Enter key is pressed in the text field display.) The method DisplayEnteredText() is used to display the text from the input field in the output field. Line 13 clears the input_text text field.

DisplayText() Method


        void DisplayText(Event evt) {
        // Display the text "Hi, Mom!" in the output field.
                if (evt.target == display_button) {
                        output_text.setText("Hi, Mom!");
                }
        }
 

This method simply checks to see whether the "DISPLAY MOM" button was pressed (in the line if (evt.target == display_button) {). If the "DISPLAY MOM" button was pressed, the text "Hi, Mom!" is displayed in the output_text text field through the call to setText(). (In our example, there is no other button that could be pressed, but the code to check which button was pressed is included here to illustrate how it can be done.)

DisplayEnteredText()


        void DisplayEnteredText() {
            // Display the text the user entered
            if (out_string != null)
                output_text.setText(out_string);
        }


This method displays the string that was typed into the input_text field (if it is not null) by using the setText() method on the output_text field.

In this section, we created a simple interactive applet (window). In the next section, we will start designing our Hilo game, which will build upon the basic concepts that were illustrated in this section.