/** * A gui-based implementation of IO. * Creates a window for displaying and getting information. * * @author Ian Barland * @version 2007.Nov.25 */ public class SimpleGuiIO { private java.awt.Frame f; /** A 0-arg constructor. */ SimpleGuiIO() { this( "a simple gui" ); } // Just call the 1-arg constructor. /** Constructor, taking the window title. * @param title The title of the window. */ SimpleGuiIO( String title ) { f = new javax.swing.JFrame( title ); f.setVisible(true); // We need this, so that the user has a way to quit the program! // (by closing this otherwise-empty frame). } /** Display a message to the game-player. * @param msg The string to display. */ public void display( String msg ) { javax.swing.JOptionPane.showMessageDialog( null, msg ); } /** Print a message to the user, and have them enter a response (one word). * @param msg A message to prompt the user with. * @return The user's response. */ public String promptForString( String msg ) { String answer = javax.swing.JOptionPane.showInputDialog( msg ); return (answer == null ? "" : answer); // Turn no-answer into "". } /** Print a message to the user, and have them enter a response (one word). * @param msg A message to prompt the user with. * @return The user's response. */ public int promptForInt( String msg ) { String answer = javax.swing.JOptionPane.showInputDialog( msg ); if (answer == null) { answer = ""; } // Turn no-answer into "". return new Integer(answer).intValue(); } public static void testIO() { SimpleGuiIO io = new SimpleGuiIO(); int selection; io.display( "This is a message." ); io.display( "This is another message." ); String msg = io.promptForString( "What is your wish?" ); io.display( "You want me to " + msg + "? Forget it!" ); int num = io.promptForInt( "What is your favorite number?" ); io.display( num + " is my favorite number, too!\n" ); } }