Images
[Agent practical 8 of 9]


We'll now test our image method by displaying the image produced on our canvas.


We now need to call the Environment object's getDataAsImage method from inside Model's paint method:

   public void paint (Graphics g) {
      Image image = world.getDataAsImage();
      Graphics cg = c.getGraphics();
      cg.drawImage(image, 0, 0, this);
   }

Test this code. You should initially see a black square in your frame. Try opening a file. If you don't see anything you may need to force the Model frame to repaint at the end of your actionPerformed method. Add the following line at the bottom of actionPerformed:

repaint();


Lastly, we need to display our agents!

Here's the code. Note that we use our polymorphic getNeighbourhood() method to get a Polygon we can draw around the agent (ok, so the neighbourhood is checked before they move to it, but it gives an indication of the area that has been checked):

for (Agent agent : agents) {
   cg.setColor(Color.GREEN);
   cg.fillOval(agent.getX() - 1,agent.getY() - 1,2,2);
   cg.drawPolygon(agent.getNeighbourhood());
   cg.setColor(Color.BLACK);
}

Add this code to the paint() method directly after the code to draw the image. If you add it before the image drawing, the agents will appear behind the image and you won't see them.

Doomed: If you run this code, you'll see that the model runs, but it doesn't update until the very end. This is because we haven't yet told the screen to repaint after each runAgents() iteration. However, even if we put a repaint() into the iterations loop, it won't make much difference. This is because of the way Java separates off code that draws to the screen. In general, code that repaints() to the screen will take second place to running other code.

However, it is possible to bypass this to an extent by directly calling the code repaint calls. At the end of your runAgents() iteration loop, between the loop through all the agents and the checking of the stopping condition, put the following:

update(getGraphics());

Your code should then work and display the agents as the move around. If it does, congratulations! You've built your core model!

You've also now got an application that reads in files, stores the data, displays it as an image, and can write the data out. If you strip out the agent elements, you're left with the foundations for almost any raster data processing tool.

We're done for this practical. If, however, you want to smarten your application up a bit, you'll find a few suggestions in here.