GUI
[Agent practical 7 of 9]
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 Model):
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());
world.setData(io.readData(f));
buildAgents();
}
}
}
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("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 Model class and passed in to IO.
Check out the GUI lecture Key Ideas page for more things you could do to improve this code.