import java.applet.*; import java.awt.*; import java.awt.event.*; import java.util.*; /* When the user clicks on the Go button, any text in the textarea is processed by dividing it up into words separated by spaces. Then these words are put in a vector and then put into a string in reverse order. The string is displayed on a canvas. However, if the user types the word Java somewhere in the middle of a sentence, a special string is printed and no reversing is performed. This program illustrates the following Java mechanisms: Use of a TextArea object. Creation of a subclass of Canvas in order to associate a special paint method with it. Use of a button to control the processing of text input. */ public class TextTestApplet extends Applet implements ActionListener { TextArea ta; TTACanvas ttaCanvas; Button goButton; String displayString = "Hi there! Type a sentence in the textarea!"; public void init() { setLayout(new BorderLayout()); ta = new TextArea(5,20); ttaCanvas = new TTACanvas(); goButton = new Button("Go"); ttaCanvas.setSize(300,200); add(ta, BorderLayout.NORTH); add(ttaCanvas, BorderLayout.CENTER); add(goButton, BorderLayout.SOUTH); ttaCanvas.setString(displayString); goButton.addActionListener(this); } public void actionPerformed(ActionEvent e) { if (e.getSource() == goButton) { StringTokenizer st = new StringTokenizer(ta.getText(), " "); Vector words = new Vector(); while (st.hasMoreTokens()) { String thisWord = st.nextToken(); if (thisWord.equals("Java")) { displayString = "You said the magic word -- Java."; ttaCanvas.setString(displayString); ttaCanvas.repaint(); return; } words.addElement(thisWord); } // Now create a reversed list of words. displayString = ""; for (Enumeration enum = words.elements(); enum.hasMoreElements();) { displayString = enum.nextElement() + " " + displayString; } ttaCanvas.setString(displayString); ttaCanvas.repaint(); } } }