//TextReverserApplet.java import java.applet.Applet; import java.awt.*; import java.awt.event.*; /** * Creates an applet containing a TextReverserPanel. * Will run as either an applet or an application. *
* If run as an applet, it can either be embedded in a webpage * or create a pop-up window. The applet behavior is * determined by the parameter "popup", which should be set * to true or false in the enclosing HTML document. * The default is to run embedded. * * @author Zach Tomaszewski * @version 05 April 2005 */ public class TextReverserApplet extends Applet { /** * Runs as an applet, either as an embedded Panel or as a pop-up Frame, * depending on this applet's parameters. */ public void init() { if ("true".equalsIgnoreCase(this.getParameter("popup"))) { //conditional above reversed to avoid NPE this.runAsFrame(); }else { this.add(new TextReverserPanel()); } } /** * Runs this applet as an application, opening a Frame. */ public static void main(String[] args){ TextReverserApplet app = new TextReverserApplet(); app.runAsFrame(); } /** * Creates a Frame ("popup" window) and sets it visible. */ protected void runAsFrame() { Frame popup = new Frame(); popup.add(new TextReverserPanel()); popup.setTitle(("Text Reverser")); popup.setSize(300, 100); //size of window popup.setLocation(200, 200); //position on screen //add an anonymous class that extends WindowAdapter to get the X //(close window) button to work. popup.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { we.getWindow().setVisible(false); try { System.exit(0); //applets don't exit like this //but applications do }catch (SecurityException se) { //oh well, didn't need to exit for applet anyway } } }); popup.setVisible(true); } }//end class /** * A panel that reverses the user's input. * Contains a text field and a "Reverse" button. * * @author Zach Tomaszewski * @version 05 Apr 2005 */ class TextReverserPanel extends Panel implements ActionListener { private Button reverseButton; private TextField inputField; /** * Creates a new Panel and adds the component button * and text field to the interface. */ public TextReverserPanel() { reverseButton = new Button("Reverse"); inputField = new TextField(20); this.add(inputField); this.add(reverseButton); reverseButton.addActionListener(this); inputField.addActionListener(this); } /** * Reverses any text in this applet's text field. */ public void actionPerformed(ActionEvent ae){ StringBuffer text = new StringBuffer(this.inputField.getText()); text.reverse(); this.inputField.setText(text.toString()); } }//end class