Java Genesis

Hints for Chapter 11: Exceptions and Files

Problem 21: improving map making

Here is code to display the message "invalid file name" whenever the 'save' button is pressed while there is no file name in the create window's text field. This code is the saveMap method of the class CreateMapPanel:
   public void saveMap (String fileName) {
        try {
           pw = new PrintWriter(new FileWriter(fileName));
           pw.println(size);
           for (int i = 0; i < size; i++) pw.println(xs[i]+" "+ys[i]);
           pw.close();
           size = 0;
           repaint();
        } catch (FileNotFoundException e) {
           System.out.println("invalid file name");
        } catch (IOException e) {
           System.out.println("Error in saving map: "+e);
           System.exit(0);
        }
   }
Only the code underlined is new. The remaining code is exactly as it appeared in the method saveMap of the class CreateMapPanel.

Try something similar with the DisplayMapPanel class.

Next Hint