Richard G Baldwin (512) 223-4758, baldwin@austin.cc.tx.us, http://www2.austin.cc.tx.us/baldwin/

The AWT Package, The TextField, TextArea, and Label Classes

Java Programming, Lesson # 134, Revised 01/14/98.

Preface

Students in Prof. Baldwin's Advanced Java Programming classes at ACC are responsible for knowing and understanding all of the material in this lesson.

Introduction

This series of lessons is concentrating on the package java.awt where most of the functionality exists for providing the user interface to your application or applet.

We have learned how to handle events in both JDK 1.0.2 and JDK 1.1 and we have learned how to use the layout managers in JDK 1.1 (which isn't greatly different from using layout managers in JDK 1.0.2). These two topics form the basis for the design and implementation of a Graphical User Interface.

The next step is to take a look at the variety of components that are available to combine with layout and event handling to produce an effective Graphical User Interface.

The available components are defined by classes in the package java.awt. Our approach will be to group those classes into categories and study the material on a category basis. We have discussed container classes and non-text classes. As of this writing, it looks as if the remaining categories will be:

However, as things develop, I may find it necessary to modify these groupings.

Text Input and Output Components

This lesson will deal with the classes TextField and TextArea along with the class Label.

The TextField class can be used to produce a component that will accept one line of user text as input. It can also be used to display one line of text in a "non-editable" fashion with a border.

The TextArea class can be used to produce a component that will accept multiple lines of user text as input. It can also be used to display multiple lines of scrollable text in a "non-editable" fashion.

TextField and TextArea extend TextComponent which extends Component.

The Label class can be used to display one line of text. This component is inherently non-editable and that attribute cannot be modified by the program.

TextField

The TextField class can be used to instantiate components that allow the editing of a single line of text. The class can also be used to display non-editable text in a single-line format with a border.

The TextField class extends the TextComponent class which extends the Component class. Thus, the many different methods which are defined in theTextComponent, Component and Object classes are also available to objects of the TextField class.

Before going on, we need to take a look at the TextComponent class which is so important to both the TextField and TextArea classes.

According to the JDK 1.1 documentation, the description of the TextComponent class, which is the superclass of both the TextField class and the TextArea class is:
"A TextComponent is a component that allows the editing of some text."
The TextComponent class has one field and no public constructors.

Therefore, it is not possible to instantiate an object of the TextComponent class.

However, the TextComponent class is the repository for a large number of methods which are inherited not only by TextField but also by other class that subclasses TextComponent.

Some of the methods of the TextComponent class which are particularly interesting include the following:
  • addTextListener(TextListener) -- Adds the specified text event listener to receive text events from this textcomponent. 
  • removeTextListener(TextListener) -- Removes the specified text event listener so that it no longer receives text events from this textcomponent 
  • getSelectedText() -- Returns the selected text contained in this TextComponent. 
  • getSelectionEnd() -- Returns the selected text's end position. 
  • getSelectionStart() -- Returns the selected text's start position. 
  • getText() -- Returns the text contained in this TextComponent. 
  • select(int, int) -- Selects the text found between the specified start and end locations. 
  • selectAll() -- Selects all the text in the TextComponent. 
  • setSelectionEnd(int) -- Sets the selection end to the specified position. 
  • setSelectionStart(int) -- Sets the selection start to the specified position. 
  • setCaretPosition(int) -- Sets the position of the text insertion caret for the TextComponent 
  • getCaretPosition() -- Returns the position of the text insertion caret for the text component. 
  • setEditable(boolean) -- Sets the specified boolean to indicate whether or not this TextComponent should be editable. 
  • isEditable() -- Returns the boolean indicating whether this TextComponent is editable or not. 
  • setText(String) -- Sets the text of this TextComponent to the specified text. 
We will be using some of these methods in the sample programs in this lesson.

Now back to our discussion of the TextField class. As of 3/13/97, the TextField class has no fields and has the following public constructors:
  • TextField() -- Constructs a new TextField. 
  • TextField(int) -- Constructs a new empty TextField with the specified number of columns. 
  • TextField(String) -- Constructs a new TextField initialized with the specified text. 
  • TextField(String, int) -- Constructs a new TextField initialized with the specified text and columns. 
Also as of 3/13/97, the TextField class provides about twenty methods, many of which are deprecated. The following partial list of methods indicates some of the capabilities available with objects of class TextField.
  • addActionListener(ActionListener) -- Adds the specified action listener to receive action events from this textfield. 
  • removeActionListener(ActionListener) -- Removes the specified action listener so that it no longer receives action events from this textfield. 
  • getColumns() -- Returns the number of columns in this TextField. 
  • setColumns(int) -- Sets the number of columns in this TextField. 
  • getMinimumSize() -- Returns the minimum size Dimensions needed for this TextField. 
  • getMinimumSize(int) -- Returns the minimum size Dimensions needed for this TextField with the specified amount of columns. 
  • getPreferredSize() -- Returns the preferred size Dimensions needed for this TextField. 
  • getPreferredSize(int) -- Returns the preferred size Dimensions needed for this TextField with the specified amount of columns. 
  • setEchoChar(char) -- Sets the echo character for this TextField. This is useful for fields where the user input shouldn't be echoed to the screen, as in the case of a TextField that represents a password. 
  • echoCharIsSet() -- Returns true if this TextField has a character set for echoing. 
  • getEchoChar() -- Returns the character to be used for echoing. 
We will make use of some of these methods as well as methods inherited from the superclasses of TextField in the following sample program.

Sample Program for TextField

This program is designed to be compiled and run under JDK 1.1

The program places a TextField object in a Frame object. The String "Initial text" is initially displayed in the TextField object at program startup.

An ActionListener object is instantiated and registered on the TextField object. An action event occurs when the user presses the Enter key while the TextField object has the focus. The purpose of the ActionListener object in this program is to extract and display the text in the TextField object in two different ways:

When the user presses the Enter key while the TextField object has the focus, an event is trapped by the overridden actionPerformed() method of the ActionListener object. Code in the overridden method uses the getSelectedText() method of the TextField class to access and display the text that has been selected by the user.

Code in the overridden actionPerformed() method also uses the getText() method of the TextComponent class to access and display all of the text in the TextField object.

A windowClosing() event listener object is instantiated and registered on the frame to terminate the program when the frame is closed.

The program was tested using JDK 1.1.3 running under Win95.

Interesting Code Fragments in TextField Program

In this section, we will concentrate on code fragments which are peculiar to the TextField class and skip over the other code.

The first interesting code fragment instantiates a TextField object with an initial text string. Then an ActionListener object is instantiated and registered on the TextField object.
    TextField myTextField = new TextField("Initial Text"); 
    myTextField.addActionListener(
                       new MyActionListener(myTextField));
There are a number of lines of code following this which we have already covered in earlier lessons. Therefore, we will skip over them.

The next interesting code fragment is the overridden actionPerformed() method which uses the getSelectedText() method from the TextField class and the getText() method from the TextComponent class to obtain and display the selected portion of the text followed by all the text.
    public void actionPerformed(ActionEvent e){
      System.out.println(
        "Selected text is: " + aTextField.getSelectedText());
      System.out.println(
                     "All text is: " + aTextField.getText());
    }//end actionPerformed()
A listing of the program complete with comments is contained in the next section.

Program Listing for TextField Program

This section contains a complete listing of the program. See the sections above for an operational description of the program.
/*File TextField01.java Copyright 1997, R.G.Baldwin
This program is designed to be compiled and run under 
JDK 1.1

The program places a TextField object in a Frame object.  

The String "Initial text" is initially displayed in the 
TextField object at program startup.

An ActionListener object is instantiated and registered on
the TextField object.  An action event occurs when the 
user presses the Enter key while the TextField object has
the focus.  The purpose of the ActionListener object is to
extract and display the text in the TextField object in two
different ways:

1.  Display all the text in the TextField object.
2.  Display only that portion of the text that has been 
    selected by by the user using any of the available 
    ways of selecting text.
    
When the user presses the Enter key while the TextField 
object has the focus, an event is trapped in the overridden
actionPerformed() method of the ActionListener object.  
Code in the overridden method uses the getSelectedText()
method of the TextField class to access and display the
text that has been selected by the user.

Code in the overridden actionPerformed() method also uses
the getText() method to access and display all of the text
in the TextField object.

A windowClosing() event listener object is instantiated 
and registered on the frame to terminate the program when
the frame is closed.

The program was tested using JDK 1.1.3 running under Win95.
**********************************************************/

import java.awt.*;
import java.awt.event.*;
//=======================================================//

public class TextField01 {
  public static void main(String[] args){
    GUI gui = new GUI();//instantiate a GUI
  }//end main
}//end class TextField01
//=======================================================//


class GUI {
  public GUI(){//constructor
    //Instantiate a TextField object and place an initial
    // String in it.
    TextField myTextField = new TextField("Initial Text");

    //Instantiate and register an ActionListener object on
    // the TextField object.    
    myTextField.addActionListener(
                        new MyActionListener(myTextField));
    
    //Place the TextField object in a Frame object
    Frame myFrame = new Frame(
                            "Copyright 1997, R.G.Baldwin");
    myFrame.setLayout(new FlowLayout());    
    myFrame.add(myTextField);
    myFrame.setSize(250,150);
    myFrame.setVisible(true);
    
    //Instantiate and register a window listener to 
    // terminate the program when the Frame is closed. 
    myFrame.addWindowListener(new Terminate());
  }//end constructor
}//end class GUI definition
//=======================================================//

//Class to listen for ActionListener events on the 
// TextField object
class MyActionListener implements ActionListener{
  TextField aTextField;
    
  MyActionListener(TextField inTextField){//constructor
    aTextField = inTextField;//save reference to TextField
  }//end constructor
  
  //Override the actionPerformed() method of the 
  // ActionListener interface.
  public void actionPerformed(ActionEvent e){
    System.out.println(
      "Selected text is: " + aTextField.getSelectedText());
    System.out.println(
                   "All text is: " + aTextField.getText());
  }//end actionPerformed()
}//end class MyActionListener
//=======================================================//

class Terminate extends WindowAdapter{
  public void windowClosing(WindowEvent e){
    System.exit(0);//terminate the program
  }//end windowClosing
}//end class Terminate
//=======================================================//
.

TextArea

According to the JDK 1.1 documentation,
"A TextArea object is a multi-line area that displays text. It can be set to allow editing or read-only modes."
Like the TextField class above, the TextArea class extends the TextComponent class meaning that all the methods defined in the TextComponent class are available to objects of the TextArea class.

As of 3/13/97, the TextArea class has four fields, all of which are constants, and all of which have to do with the establishment of horizontal and vertical scrollbars for a TextArea object. A list of these symbolic constants will be provided later.

Also as of 3/13/97, the TextArea class has the following public constructors:
  • TextArea() -- Constructs a new TextArea. 
  • TextArea(int, int) -- Constructs a new empty TextArea with the specified number of rows and columns. 
  • TextArea(String) -- Constructs a new TextArea with the specified text displayed. 
  • TextArea(String, int, int) -- Constructs a new TextArea with the specified text and number of rows and columns. 
  • TextArea(String, int, int, int) -- Constructs a new TextArea with the specified text and number of rows, columns, and scrollbar 
The symbolic constants that can be used to specify information about the scrollbar in the fourth version of the constructor are:
  • SCROLLBARS_BOTH Create and display both vertical and horizontal scrollbars. 
  • SCROLLBARS_HORIZONTAL_ONLY Create and display horizontal scrollbar only. 
  • SCROLLBARS_NONE Do not create or display any scrollbars for the text area. 
  • SCROLLBARS_VERTICAL_ONLY Create and display vertical scrollbar only. 
As of 3/13/97, the TextArea class contains about twenty-one methods, many of which are deprecated. A few of the particularly interesting methods follow:
  • append(String) -- Appends the given text to the end. 
  • insert(String, int) -- Inserts the specified text at the specified position. 
  • replaceRange(String, int, int) -- Replaces text from the indicated start to end position with the new text specified. 
Don't forget that there many other methods defined in the TextArea class and in the TextComponent, Component, and Object classes that are also available to objects of the TextArea class.

Sample Program for TextArea Class

This program is designed to be compiled and run under JDK 1.1

The program places a TextArea object in a Frame object. The TextArea object is specified to have a vertical Scrollbar.

An initial string consisting of ten separate lines of text is placed in the TextArea object when it is instantiated.

A TextListener object is instantiated and registered on the TextArea object. A TextEvent occurs whenever there is a change in the value of the text contained in the TextArea object.

The purpose of the TextListener object in this program is to display all of the text in the TextArea object whenever its value changes.

When the text value changes in the TextArea object, an event is trapped by the overridden textValueChanged() method of the TextListener object. Code in the overridden textValueChanged() method uses the getText() method of the TextComponent class to access and display all of the text in the TextArea object.

Note that this program is processing text at a very low level. An event occurs every time an individual character changes.

A windowClosing() event listener object is instantiated and registered on the frame to terminate the program when the frame is closed.

The program was tested using JDK 1.1 running under Win95.

Interesting Code Fragments from TextArea Program

This section will concentrate on only that portion of the code that is peculiar to the TextArea class and the TextListener interface.

The first interesting code fragment is the code used to instantiate the object of the TextArea class with a vertical scrollbar and then place ten separate lines of text in the object. Note that the append() method of the TextArea class is used to place the text in the object. Any of several other methods could also have been used for that purpose.
TextArea myTextArea = 
  new TextArea("", 5, 20,  TextArea.SCROLLBARS_VERTICAL_ONLY);
for(int cnt = 0; cnt < 10; cnt++) 
  myTextArea.append("Line " + cnt + "");
The next interesting code fragment instantiates and registers a TextListener object on the TextArea object.
myTextArea.addTextListener(new MyTextListener(myTextArea));
The final interesting code fragment is the overridden textValueChanged() method that uses the getText() method of the TextComponent class to access and display all the text in the TextArea object whenever there is a change in the value of the text in the object.
    public void textValueChanged(TextEvent e){
      System.out.println(aTextArea.getText());
    }//end textValueChanged()
A complete listing of the program is provided in the next section.

Program Listing for TextArea Program

This section contains a complete listing of the program with additional comments. See the sections above for an operational description of the program.
/*File TextArea01.java Copyright 1997, R.G.Baldwin
This program is designed to be compiled and run under 
JDK 1.1

The program places a TextArea object in a Frame object. The
TextArea object is specified to have a vertical Scrollbar.

An initial string consisting of 10 separate lines of text 
is placed in the TextArea object when it is instantiated.

A TextListener object is instantiated and registered on 
the TextArea object.  A TextEvent occurs whenever there is
a change in the value of the text contained in the TextArea
object. The purpose of the TextListener object is to 
display the text in the TextArea object whenever its value
changes.
    
When the text value changes in the TextArea object, an 
event is trapped by the overridden textValueChanged() 
method of the TextListener object. Code in the overridden
textValueChanged() method uses the getText() method of the
TextComponent class to access and display all of the text 
in the TextArea object.

Note that this program is processing text at a very low 
level - every time a character changes.

A windowClosing() event listener object is instantiated and
registered on the frame to terminate the program when the
frame is closed.

The program was tested using JDK 1.1.3 running under Win95.
**********************************************************/


import java.awt.*;
import java.awt.event.*;
//=======================================================//

public class TextArea01 {
  public static void main(String[] args){
    GUI gui = new GUI();//instantiate a GUI
  }//end main
}//end class TextArea01
//=======================================================//

class GUI {
  public GUI(){//constructor

    //Instantiate a TextArea object with a vertical 
    // scrollbar and initialize the object with ten lines
    // of text.
    TextArea myTextArea = new TextArea(
        "", 5, 20,  TextArea.SCROLLBARS_VERTICAL_ONLY);
    for(int cnt = 0; cnt < 10; cnt++)
      myTextArea.append("Line " + cnt + "\n");
    
    //Instantiate and register a TextListener object on the
    // TextArea object.    
    myTextArea.addTextListener(
                           new MyTextListener(myTextArea));
    
    //Place the TextArea object in a Frame object
    Frame myFrame = new Frame(
                            "Copyright 1997, R.G.Baldwin");
    myFrame.setLayout(new FlowLayout());    
    myFrame.add(myTextArea);
    myFrame.setSize(250,150);
    myFrame.setVisible(true);
    
    //Instantiate and register a window listener to 
    // terminate the program when the Frame is closed. 
    myFrame.addWindowListener(new Terminate());
  }//end constructor
}//end class GUI definition
//=======================================================//

  //Class to listen for TextListener events on the 
  // TextArea object
  class MyTextListener implements TextListener{
    TextArea aTextArea;
    
    MyTextListener(TextArea inTextArea){//constructor
      aTextArea = inTextArea;//save a reference
    }//end constructor
    
    //Override the textValueChanged() method of the 
    // TextListener interface.
    public void textValueChanged(TextEvent e){
      System.out.println(aTextArea.getText());
    }//end textValueChanged()
  }//end class MyTextListener
//=======================================================//

class Terminate extends WindowAdapter{
  public void windowClosing(WindowEvent e){
    System.exit(0);//terminate the program  
  }//end windowClosing
}//end class Terminate
//=======================================================//
.

Label

An object of class Label is an object that can be used to display a single line of read-only text. It is not possible for the user to enter text into a Label object.

The Label class extends the Component class.

As of 3/13/97, the Label class has the following fields which are all constants. The names of the fields are self-explanatory.
  • CENTER The center alignment. 
  • LEFT The left alignment. 
  • RIGHT The right alignment. 
Also as of 3/13/97, the Label class has the following public constructors:
  • Label() -- Constructs an empty label. 
  • Label(String) -- Constructs a new label with the specified String of text. 
  • Label(String, int) -- Constructs a new label with the specified String of text and the specified alignment. 
These are self-explanatory as well.

As of 3/13/97, the Label class has six methods mostly involved with getting and setting text and dealing with alignment. For our purposes in this lesson, the most interesting subset of the available methods follows:
  • getAlignment() Gets the current alignment of this label. 
  • getText() Gets the text of this label. 
  • setAlignment(int) Sets the alignment for this label to the specified alignment. 
  • setText(String) Sets the text for this label to the specified text. 
The next section contains a very simple program showing how to use an object of the Label class in its most common form -- a read-only single line of text.

The program does not provide any event handling because events are not ordinarily generated by labels.

Remember however that since the Label class is a subclass of the Component class, any of the low-level event listeners defined in that class apply to Label objects also.

Therefore, Label objects can be the sources of low-level events, and event listener objects can be instantiated and registered on those Label objects.

You might want to go back and review some of the lessons on event handling in JDK 1.1 where it was shown that contrary to normal operation, objects of the Label class can generate low-level events such as mouse events, key events, and focus events.

Sample Program for the Label Class

This program is designed to be compiled and run under JDK 1.1

The program places a Label object in a Frame object. The string "Initial Text" is placed in the Label object when it is instantiated.

The Label object behaves as a non-editable single line of text and doesn't generate events (at least there are no listener objects registered to listen for events).

A windowClosing() event listener object is instantiated and registered on the frame to terminate the program when the frame is closed.

The program was tested using JDK 1.1 running under Win95.

Interesting Code Fragments from the Label Program

For purposes of this lesson, the only interesting code fragment in this program is the instantiation of the Label object as follows:
Label myLabel = new Label("Initial Text");
A complete listing of the program is provided in the next section.

Program Listing for the Label Program

This section contains a complete listing of the program with comments. For an operational description of the program, see the previous sections of this lesson.
/*File label3.java Copyright 1997, R.G.Baldwin
This program is designed to be compiled and run under 
JDK 1.1

The program places a Label object in a Frame object. The 
string "Initial Text" is placed in the Label object when 
it is instantiated. 

The label object behaves as a read-only single line of 
text and doesn't generate events.

A windowClosing() event listener object is instantiated 
and registered on the frame to terminate the program when
the frame is closed.

The program was tested using JDK 1.1.3 running under Win95.
**********************************************************/

import java.awt.*;
import java.awt.event.*;
//=======================================================//

public class label3 {
  public static void main(String[] args){
    GUI gui = new GUI();//instantiate a GUI
  }//end main
}//end class label3
//=======================================================//

class GUI {
  public GUI(){//constructor

    //Instantiate a Label object with an initial text 
    // string.
    Label myLabel = new Label("Initial Text");
    
    //Place the Label object in a Frame object
    Frame myFrame = new Frame(
                            "Copyright 1997, R.G.Baldwin");  
    myFrame.setLayout(new FlowLayout());    
    myFrame.add(myLabel);
    myFrame.setSize(250,150);
    myFrame.setVisible(true);
    
    //Instantiate and register a window listener to 
    // terminate the program when the Frame is closed. 
    myFrame.addWindowListener(new Terminate());
  }//end constructor
}//end class GUI definition
//=======================================================//

Review

Most of the previous lessons have provided review problems and review questions to reinforce the material presented in the lesson.

It is this author's belief that by the time you reach this point in your study of Java programming, you should be working at a sufficiently independent level that such review information should no longer be necessary.

In particular, you should be working at a level that allows you to create your own review questions and programs, particularly tuned to the work that you are doing in Java.

Therefore, review questions and programs will rarely be provided for the remaining lessons in this set of Java programming tutorials.

-end-