RingJavafor Ring

Animation

A timer calls a Ring function that draws the next picture.

What you will learn#

The program#

samples/UsingJava/tutorials/ch21_animation.ring
# 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++
A frame of the animation
ch21_animation.ring

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#

  1. Make the ball faster when you click.
  2. Add a second ball.
  3. Stop the timer with a button.

Next#

Queries

RingJava - use Java classes and methods from Ring programs.