/** * A gui-based implementation of IO. * Creates a window for displaying and getting information. * * @author Ian Barland * @version 2006.Dec.01 */ public class SimpleGuiIO implements IO { public static int NO_SELECTION = -1; // This value must not be a valid index. // Really, this named constant should be declared inside interface IO, // but I didn't specify that before the homework was posted. /** Display a message to the game-player. * @param msg The string to display. */ public void display( String msg ) { javax.swing.JOptionPane.showMessageDialog( null, msg ); } /** Return a nice-looking string listing & numbering the contents of ds. * @param ds The list of Describable items. * @return a nice-looking string listing the contents of ds, * numbered from 1..size. */ private static String describablesToString( java.util.ArrayList ds ) { String stringSoFar = ""; for ( int i = 0; i < ds.size(); ++i ) { stringSoFar += " " + (i+1) + ") " + ds.get(i).getName() + "\n"; } return stringSoFar; } /** Have the user select an item from a list displayed on the console window. * @param instruction A message describing what is being selected, e.g. "a treasure to grab" * @param items The list of items to get a choice from. The list will not be modified. * @return an index into items. */ public int select( String instruction, java.util.ArrayList items ) { String answer = javax.swing.JOptionPane.showInputDialog( describablesToString( items ) ); int numberChoice; try { numberChoice = Integer.parseInt( answer ) - 1; } catch (NumberFormatException e) { numberChoice = NO_SELECTION; } if ((0 <= numberChoice) && (numberChoice < items.size())) { return numberChoice; } else { return NO_SELECTION; } } /** 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 prompt( String msg ) { String answer = javax.swing.JOptionPane.showInputDialog( msg ); return (answer == null ? "" : answer); // Turn no-answer into "". } public static void testIO() { IO io = new SimpleGuiIO(); int selection; io.display( "This is a message." ); io.display( "This is another message." ); java.util.ArrayList ts = new java.util.ArrayList(); ts.add( new Treasure( "nameA", "descrA", 4) ); selection = io.select("get a treasure", ts); io.display( "You selected " + (selection == NO_SELECTION ? "nothing" : ts.get( selection ).getName() )); ts.add( new Treasure( "nameB", "descrB", 4) ); selection = io.select("get another treasure", ts); io.display( "You selected " + (selection == NO_SELECTION ? "nothing" : ts.get( selection ).getName() )); ts.add( new Treasure( "nameC", "descrC", 4) ); selection = io.select("get one last treasure", ts); io.display( "You selected " + (selection == NO_SELECTION ? "nothing" : ts.get( selection ).getName() )); } }