Rexx Magnus <trashcan@uk2.net> writes:
I've got some code below, in its early stages - my ultimate goal is
to be able to render pixel graphics to the screen, but I don't want
to render an entire image and then display it. I'd prefer to have it
shown as it draws, so that I can see the activity (for the time being).
I would like to try to summarize how to do animation.
This is somewhat daring, because I never actually wrote
anything like this myself:
The method that paints an on-screen area usually is called
?paintComponent?. Whenever it is being activated, it should
synchronize the model (internal state of the painting) to
the screen (output area).
To make sure that ?paintComponent? is being activated,
one can call ?repaint?.
For ?paintComponent? to be executed on a regular base one
thread needs to call repaint() repeatedly. Usually this will
be done with the update frequency wanted.
Special care might be necessary if the update frequency should
be ?as fast as possible?: Then the time between two calls of
?repaint()? should be significantly smaller then the run time
of a single paintComponent(). This run time, however, is not
known when writing the program. So, one might measure it at
run time and then call repaint() after 1/20 of it? Multiple
calls of repaint() will be coalesced by Swing when they arrive
while paintComponent() is still running, so that this should
be harmless.
The behavior of paintComponent() depends on whether this is a
continous animation depending on the time or a stepped
calculation proceeding in generations. In the first case, the
picture is calculated for the current time. In the second
case, the next generation is calculated and then being displayed.
Both, however, might conflict recommendations not to
do long calculations within the event-dispatch thread.
When the calculation of the next generation is being done
within ?paintComponent?, one can assume a quite regular loop:
One execution of paintComponente does ?calculate();
display();?; and fast triggering via ?repaint? will start this
anew as soon as it has been finished. This results in a
calculate-display-iteration.
Another approach would be to draw into a memory buffer from an
extra thread. paintComponent() will be called whenever the
buffer has been changed significantly. When the programm does
not have to be fast, one might want to repaint() after every
pixel changed. If it should be fast, one might do several
modifications to the picture before the next ?repaint? is
called. I.e., one might like to keep paintComponent from
taking to much processing time away from the other thread.
Two other notes:
One can add additional care not to repaint faster than the
hardware video refresh cylce for a full screen, or much faster
than the eyes can see because more speed would be wasted.
I believe, there also is a full-screen mode for Java, where
some rules may change. For example, one might not have to
worry about overlapping or moving windows in this case.