An example of text fields in Java

A better pattern extra methods in the CapitalizeApplet class and does not expose CapitalizeApplet's private fields.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;


public class CapitalizeApplet extends Applet {

  private TextField input;
  private TextField output;
  
  public void init () {
   
     // Construct the TextFields
     this.input = new TextField(40);
     this.output = new TextField(40);
     this.output.setEditable(false);
     Button b = new Button("Capitalize");

     // add the button to the layout
     this.add(input);
     this.add(b);
     this.add(output);

     // specify that action events sent by the
     // button or the input TextField should be handled 
     // by the same CapitalizerAction object
     CapitalizerAction ca = new CapitalizerAction(this);
     b.addActionListener(ca);
     this.input.addActionListener(ca);

     // notice that ActionEvents produced by output are ignored.
   
  }
   
  public void capitalize()  {
  
    String s = input.getText();
    output.setText(s.toUpperCase());  
    
  } 

}


class CapitalizerAction implements ActionListener {

  private CapitalizeApplet target;

  public CapitalizerAction(CapitalizeApplet target) {
    this.target = target;
  }

  public void actionPerformed(ActionEvent ae) {

    target.capitalize();

  }

}

Previous | Next | Top | Cafe au Lait

Copyright 2001-2003 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified November 6, 2003