GUI
[Agent practical 7 of 9]


This practical we're going to build a GUI for our model.

We're going to make our application extend Frame, so we can see it as a Window, and then add a menu so we can run our readData and writeData methods from the GUI.


First off, let's get our app a windows-based GUI.

Copy last practical's code into a new directory for framework7. Delete the following lines from Model.java, which we mainly wrote last practical:

IO io = new IO();
world.setData(io.readData());
buildAgents();
runAgents();

io.writeData(world.getData());

We're going to get this code working from the GUI.


First up, let's make the Model class extend Frame. We'll need to import java.awt.* and we might as well import java.awt.event.* at the same time, as we'll need it later. In the same way that we've simplified our constructor before by pushing code into separate methods, let's make ourselves a method that sets up the GUI. Here's the structure of our new Model class:

import java.awt.*;
import java.awt.event.*;

public class Model extends Frame {

   public Model () {

      buildGui();

   }


   public void buildGui() {
      // Code for this practical.
   }


   // Other methods.

   public static void main (String args[]) {
      new Model();
   }

}

Get your Model code in the form above, then add in the code to set the size of the Frame (to 300 by 300) and set its visibility to 'true'. Remember, we've inherited these methods from Frame - we don't need an object to use them. Compile and Run the file.

Make sure you set the Frame size before you set it as visible. Indeed, in general you should try to do pretty much all you need to do to the GUI before you set it as visible for the user.


Remember that if you want to shut the window at the moment you'll have to use Ctrl-C at the command line. You can fix this, if you like, by adding the anonymous inner class we saw in the lecture. It would go inside the buildGui() (as we've now extended Frame, we've invisibly picked up the addWindowListener method). This is one of the few cases where you can put a class inside another, and a method inside a method.


Next, go on to Part Two, where we'll set up a menu.