|
There are two user interface components that enable a person to type in text. One is a "TextField" (a single line of text) and one is a "TextArea" (multiple lines of text). Experiment with the applet below to see what it does. Then proceed to understand the code that generates the applet.
For an applet to use a "TextField" or a "TextArea" it must implement a "TextListener" interface. Consulting the event handling reference, a "TextListener" interface requires a "textValueChanged" method to be implemented. In the example below, a "TextField" named "nameField" and a "TextArea" named "commentArea" are used. The "init" method begins by activating the null layout manager and setting the value of "message" to the empty string. It then instantiates a "TextField", locates and sizes it with the "setBounds" method, adds it to the display, and adds a listener that will respond to various text events. The "init" method now instantiates a "TextArea", sets its size and location, adds it to the display, and adds a listener for it. Notice that when the null layout manager is being used, we will always have to set the width and height of a component (unless we want it to default to 0 by 0) and its location (unless we want it to default to the upper left corner of the display area). In the "textValueChanged" method, a "getText" method is called to read the text that is currently in the "nameField". Then "repaint" is called to update what is being displayed. The "paint" method is fairly straight-forward. It provides a text label for both "nameField" and "commentArea". Then it checks to see what the current contents of the "nameField" is. If it isn't the empty string, a greeting message is displayed in the middle of the top of the display area. import java.awt.*; import java.awt.event.*; import java.applet.*; public class Example extends Applet implements TextListener { public void init() { setLayout(null); message = ""; nameField = new TextField(); nameField.setBounds(100, 100, 100, 30); add(nameField); nameField.addTextListener(this); commentArea = new TextArea(); commentArea.setBounds(100, 200, 100, 100); add(commentArea); commentArea.addTextListener(this); } public void textValueChanged(TextEvent evt) { message = nameField.getText(); repaint(); } public void paint (Graphics g) { g.drawString("Name: ", 100, 90); g.drawString("Comments: ", 100, 190); if (! message.equals("")) g.drawString("Hi " + message, 100, 50); } private TextField nameField; private TextArea commentArea; private String message; } |