Animation
A timer calls a Ring function that draws the next picture.
What you will learn#
jTimer(ms, "function"),- drawing a frame on an image and repainting a label,
- keeping the state of the animation in global variables.
The program#
# Tutorial 21: animation - a timer calls a Ring function, the function draws the next picture
load "java.ring"
using {
"javax.swing"
"java.awt"
"java.awt.image"
}
nW = 360
nH = 240
nX = 40
nY = 40
nDX = 5
nDY = 4
nFrames = 0
oImage = (new BufferedImage).@New([nW,nH,1])
oLabel = new JLabel(new ImageIcon(oImage))
oFrame = new JFrame("Animation")
oFrame.setDefaultCloseOperation(2)
oFrame.add(oLabel)
oFrame.pack()
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
# a Swing timer: every 30 ms the function step runs
oTimer = jTimer(30,"step")
oTimer.start()
jAutoClose()
jMainLoop()
oTimer.stop()
? "frames drawn: " + (nFrames > 10)
func step aArgs
nX += nDX
nY += nDY
if nX < 0 or nX > nW - 40
nDX = -nDX
ok
if nY < 0 or nY > nH - 40
nDY = -nDY
ok
g = oImage.createGraphics()
g.setColor(jColor(20,20,40))
g.fillRect(0,0,nW,nH)
g.setColor(jColor(240,90,60))
g.fillOval(nX,nY,40,40)
g.setColor(jColor(255,255,255))
g.drawString("frame " + nFrames,10,20)
g.dispose()
oLabel.repaint()
nFrames++
How it works#
The timer runs the function every few milliseconds on the Ring thread. The function changes the variables, draws on the image and calls repaint. The applications in the next chapter use the same idea.
Exercises#
- Make the ball faster when you click.
- Add a second ball.
- Stop the timer with a button.