import java.awt.*; import java.awt.event.*; /** * Greet the user. * * The class serves as the listener for its own frame, * providing a windowClosing method. It also serves as * the listener for its buttons, providing an appropriate * actionPerformed method. * * @author Samuel A. Rebelsky * @version 1.0 of February 1999 */ public class GreetGUI extends WindowAdapter implements ActionListener { // +--------+-------------------------------------------------- // | Fields | // +--------+ /** The frame used for interaction. */ protected Frame gui; /** The field in which the user enters a name. */ protected TextField userName; /** The button the user presses. */ protected Button greet; /** The area used for output. */ protected Label out; // +--------------+-------------------------------------------- // | Constructors | // +--------------+ /** Set up the frame for interaction. */ protected GreetGUI() { // Create the frame (the window). gui = new Frame("Greetings"); gui.setLayout(new FlowLayout()); gui.addWindowListener(this); // Create the entry field. Initialized to have a number of // spaces so that there is room for the user to enter a name. userName = new TextField(" "); // Create the button. greet = new Button("Hi!"); greet.addActionListener(this); // Create the output field. Right now, we'll use it for // instructions. out = new Label("Enter your name and press the button."); // Add the components to the interface. gui.add(userName); gui.add(greet); gui.add(out); gui.pack(); // And we're ready to go. gui.show(); } // GreetGUI() // +----------------+------------------------------------------ // | Event Handlers | // +----------------+ /** React to a click on the button. */ public void actionPerformed(ActionEvent evt) { // Update the output out.setText("Hi there " + userName.getText() + ", welcome to this program."); } // actionPerformed(ActionEvent) /** React to the closing of the window. */ public void windowClosing(WindowEvent event) { gui.dispose(); System.exit(0); } // windowClosing() // +------+---------------------------------------------------- // | Main | // +------+ /* Start the ball rolling by creating an object. */ public static void main(String[] args) { new GreetGUI(); } // main(String[]) } // class GreetGUI