Thursday, 14 May 2015

TextField in Java

Text fields are designed to be used to allow the user to input short pieces of text-usually no more than a few words or a single number. You also can use them to display information to the user, such as a phone number or the current sum of the costs of the items the user is going to order. Because TextField extends TextComponent, you can define whether the user can edit the contents of a TextField. The example in Listing 17.23 shows the various types of text fields you can create.

Listing 17.23. Creating TextFields.
import java.awt.*;
import java.applet.Applet;


public class text_field extends Applet
{
    TextField t[];
    Label  l[];
    int n_fields;
    GridLayout gl;

    public void init(){
        int i;

        //This defines a new layout manager with 4 rows and 2 columns
        //You'll learn about layout managers in a few pages
        gl = new GridLayout(4,2); 
        //tell the applet to use this new layout manager
        //rather than the default one
        setLayout(gl); 

        n_fields = 4; 
        t = new TextField[n_fields]; 
        l = new Label[n_fields]; 
        //set up the labels and text fields
        t[0] = new TextField(); 
        l[0] = new Label("TextField no input params");
        t[1] = new TextField(35); 
        l[1] = new Label("35 character wide TextField");
        t[2] = new TextField("Merry Christmas!");
        l[2] = new Label("TextField with initial text");
        t[3] = new TextField("Enter your Swiss bank account #",20);
        l[3] = new Label("TextField with initial text and fixed width");
        //add all the components to the applet panel
        for(i=0;i<n_fields;i++){ 
            add(l[i]); 
            add(t[i]); 
        }

    }

}


No comments:

Post a Comment