Copyright (c) SEMM NL All rights reserved.
Author : Paul Hamaker. Part of JavaLessons.com
In this program, the coordinates of tiny oval shapes are stored once in two memory arrays .
Because this is an applet, ....
the init method is executed first and here memory is set aside for 500 ints each ( 2000 bytes per array ).
Then a block of statements is started that will be executed 500 times .
The first time the block is executed, x is set to zero.
We'll use a double variable .
In it, a random number between 0 and 1 is stored :
This is multiplied :
and copied as an int into ar1 [ 0 ] :
Because ar1's data type is int , we can't store a double in it, so we CAST it to the proper type .
...... ( int ) r1 ..
This doesn't mean that r1 changes, but an int copy of r1 is made and stored in the array.
If r1 were 345.562212, for example, 345 would be stored in the array.
The number that's stored will never exceed 349, which is the width of the applet .
The statement could be more concise, as is shown with the second array :
After this x is incremented by one ....
and the block is executed again because x is still less than 349,....
so two ints are generated again and stored in their arrays.
As said before, same thing is done 500 times, so the arrays are filled entirely.
The paint method is called automatically, when needed, for instance, when the applet appears for the first time.
In the paint method the array-elements are used as coordinates to paint tiny oval shapes :
The first two parameters of Graphics' fillOval method are the x- and y-coordinates,....
while the third and fourth represent the ovals' width and height.
This is done repeatedly, too, of course, first in a set of 401 reps, ....
followed by one of 99 :
The advantage of storing painting-related data is that the applet will look the same every time it is drawn again.
Automatically, if the applet was covered, or upon request, by issuing a repaint command.
General principle is, to take care of the paint-administration, as it were, outside of the paint method.
Instead of this, you can code :
int [ ] ar1 = new int [ 500 ] ;
int [ ] ar2 = new int [ 500 ] ;
on these lines.
We've done it separately, to show that there are two steps involved in creating arrays.
One advantage of this approach is, that you can create an array during run-time, using a variable instead of the hard-coded value 500, for example.
This is generally coded on one line :
for ( int x = 0 ; x <= 499 ; x++ )
The Math class' full name is
and it contains many mathematical methods, like :