Images
[Agent practical 8 of 9]


This practical we're going to finish our model by making it display our data as an image.


Make a copy of last practical's code into a framework8 directory. The first thing we're going to do is add a paint method to our Model class.

We could just paint our model directly onto our Frame. However, with data that is updated very regularly this doesn't tend to work very well, Frames aren't really set up for data drawing, and tend to flicker badly if you update them regularly. Instead we'll add a java.awt.Canvas to our Frame, and draw on that. We'll still use the Frame's paint method, but rather than using the Frame's Graphics object, we'll use the Canvas'.

Here's the core core, with everything else removed. Add it to your model.

import java.awt.*;

private Canvas c = new Canvas();

public class Model extends Frame implements ActionListener {

   public Model () {

      buildGui();
      buildAgents();
   }


   public void buildGui() {

      add(c);

      // Menu building code.

   }


   // Other methods.

   public void paint(Graphics g) {

      Graphics cg = c.getGraphics();
      // Code using cg to draw, not g.


   }


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

}

For the moment we'll just write some text to the frame so we know it works. Using your notes make the paint method in Model write "Hello World" to the canvas. Test this works and "Hello World" stays even if you minimize and maximize the frame. Note that a handy tip with adding things to a Frame is to check they've been added/their size by setting their background temporarily to a different Color, so: c.setBackground(Color.PINK) for example. Note, also, in the above, that because of the way in which Java separates off code that draws to the screen, the Graphics object *has* to be got in the paint() method -- you can't set it up as an instance variable.


Ultimately this is where we want to get our image to, however, we need to deal with a few stages before then. We need to make a new method in our Environment class that will return an image to us, however, before that we need a couple of methods to get our data into the right format.

Go on to Part Two, where we'll look at these methods.