2. Drawing in an applet This will give us an ellipse (or "oval") whose measures are dependent on the "enclosing rectangle", like this: g.drawRect (x, y, width, height);A circle is really an ellipse of equal width and height. Let's draw a circle whose centre is the same as the centre of the applet window. But as you can see, the centre plays no part at all in the method drawOval (x,y,width, height). So we'll have to do a few calculations. In the diagram below you can see that x and y can be calculated if you know the coordinates of the centre (xm, ym) and the radius (r). So: x = xm - r The applet window used in this tutorial is 320 pixels wide and 240 pixels high. So we can calculate x and y (for a circle with a radius of 100 pixels in the middle of the applet window) as follows: x = 320/2 - r = 160 - 100 = 60The following applet draws the circle: // A circle drawn through theIf we want to give this circle a different radius, we would have to change all four numbers mentioned after drawOval - whereas it is in fact just one thing that changes: the radius. It would be much better if we make use of variables.We can store the length (100 pixels) of the radius as follows: This reserves a piece of memory for storing a whole number - or integer (int),
which we call radius. We can also store the width and height of the
applet window into variables in this way:
The use of variables makes programs more efficient and a lot easier to adapt.
With variables our circle-applet looks like this:
Variables with text: stringsThe variables we have seen so far were of
the type int (integers, whole numbers).
A very special sort of variables are the so-called strings. They consist of series of characters. They can contain any sort of character, for example: String name = "Linus Torvalds";Later in this tutorial you'll see that strings offer interesting possibilities. But you can't calculate with them. Just look at this program code: String s1 = "12", s2 = "13";The output (below) maybe somewhat surprising:
Main Menu Java Tutorial To homepage (c) 2005, Thomas J.H. Luif |