An Applet With Text Fields


The applet's real estate is the area within the border

Source

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

public class AnAppletWithTextFields extends Applet implements ActionListener {
	public void init() {
		Label label1 = new Label("First text field: ");

		textField1 = new TextField("Hello");

		swapEm = new Button("Swap");
		swapEm.addActionListener(this);

		Label label2 = new Label("Second text field: ");

		textField2 = new TextField("Goodbye");
		textField2.setEditable(false);

		add(label1);
		add(textField1);
		add(swapEm);
		add(label2);
		add(textField2);
	}

	public void actionPerformed(ActionEvent e) {
		String temp = textField1.getText();
		textField1.setText(textField2.getText());
		textField2.setText(temp);
	}

	TextField textField1, textField2;
	Button swapEm;
}

Description and Objective

An applet with some text fields and a button that exchanges their contents.

Notes

TextFields Using a TextField

This Applet's Behavior

Things to Do

API work Playing With the Applet Place the following applets on the same page:
  1. Add a button to clear out the values of the two fields; and only swap the fields if the first is greater than the second (if the first is less than or equal, display a message on the console).
  2. One of the following two (feel free to do both :) ):
    • Somewhat reminiscent of the second applet of the AppletWithParameters assignment: have three editable text fields labelled operand1, operator, and operand2, and a fourth read-only text field labelled result. Have a button labelled Calculate. WHen the button is clicked the appropriate operator is applied to the two operands and the resulting value placed in the result text field. If the operator is invalid, send a message to System.err<.code>
    • Look up the TextArea class in the API. Place a text area labelled document, and a text field labelled search for on the applet. Look up the indexOf method for String-- it allows you to look for one string within another (like find of the C++ string). Have a button labelled Search, which when clicked looks for the first occurrence of the search for field in the document area. The resulting (or an indication that it wasn't found) should be displayed in a non-editable text field. (Optional-- investigate the setCaretPosition method of the TextComponent class which is the parent class of TextArea and, in addition to displaying the found position in the text field also sets the caret (i.e., the cursor) to the corresponding position in the document area).