General Programming Notes

Drawing Graphical Elements.

Given I had trouble wrapping my head around drawing rectangles (GRec) and ovals (GOval) in Java, here’s a breakdown.

First off, to place the first pixel, you need to determine the size of the graphics window.

To find the x dimension: getWidth.  Thus the centre is getWidth/2.

To find the y dimensions getHeight.  Thus the centre is getHeight/2.

To draw a circle in the center of the screen, you need to know that the first pixel is placed at the top left of the graphical element, not the center (think you are drawing a square or rectangle and not an oval).  Thus, you need to displace the “center” by half the width of the radius.

An example of this code is:

  1. private static final double CENTRE_TARGET = 48
  2. private double startX;
  3. private double startY:
  4. startX = getWidth()/2;
  5. startX = getheight()/2;
  6. double x = CENTRE_TARGET;
  7. double y = CENTRE_TARGET;
  8. GOval target = new GOval (startX – x, startY – y, 2*x, 2*y);

I’m assigning double to the values in case the outcome of the calculation involves a decimal.  If I used int and the result was 2.1 or 10.9, the result would be 2 or 10 as code truncates (forget about rounding here), and the resultant graphical element might look wonky.  The first x, y coordinate is the start of the circle and the second x, y elements is how big  – the diameter.

What the GOval code translates to is…

“Draw a round graphic element that begins at the x coordinate that is in the center of the screen minus the radius of the circle and where the y coordinate is in the center of the screen minus the radius of the circle and where size of the circle is two times the radius (so the diameter) in both the x and y directions.”

For those who need to see this, I’ve got a couple of drawn diagram which should explain how things are done.

Finds the size and center of the graphics window in Java – 0, 0 is TOP LEFT

Diagram 2 - Draws a circle

Draws a circle in Java

Assigning Variables and Constants

Work out everything, and I mean EVERYTHING that has a number assigned to it and whack it outside the run process.  That way, if a number needs to be changed, the programmer (you or a successor) can change the value once and does not need to scour code to change each and every instance of the reference.

By convention, constants go above the run.  Variables come at the bottom.