File I/O
[Framework practical 6 of 7]


Last practical we hard-wired in our filenames. This practical we could add in a FileDialog to allow the user to open the files.


Some of FileDialog's constructors take in a Frame object, so if we're going to use one it makes sense to do this where we have a Frame. In our case, this would be in our MenuListener, as that's also our Frame extending class. Given this, we could change the code calling our IO class to this (you'll need to import java.io.* into Analyst):

   public void actionPerformed(ActionEvent e) {
      MenuItem clickedMenuItem = (MenuItem)e.getSource();
      if (clickedMenuItem.getLabel().equals("Open...")) {
         FileDialog fd =
            new FileDialog(this, "Open File", FileDialog.LOAD);
         fd.setVisible(true);
         File f = null;
         if((fd.getDirectory() != null)||( fd.getFile() != null)) {
            f = new File(fd.getDirectory() + fd.getFile());
            store.setData(io.readData(f));
         }
      }
   }

That is, we get the FileDialog to make a new File object and pass it into our readData method in IO. We'd obviously then need to change IO so its readData method started not like this:

   public double[][] readData() {
      File f = new File("m:/GEOG5XXXM/src/unpackaged/framework6/in.txt");

But like this:

   public double[][] readData(File f) {

We can then use the file f as before; the only difference is that rather than this being hardwired in inside IO, it is created within the Analyst class and passed in to IO.

Check out the GUI lecture Key Ideas page for more things you could do to improve this code.