RingJavafor Ring

Window builders

A window, the usual controls, layouts, menus and a drawing surface in one line each (libraries/javalib/swing.ring).

The helpers return the objects of Swing (JFrame, JPanel, JButton ...), so every Swing method still works on them. They load the Swing classes and switch the program to GUI mode by themselves: a program that only uses the helpers needs no using { }.

Ring
load "java.ring"

oWin = jWindow("Hello",320,160)
oName = jField("",16,"")
oWin.add([jBorder(
		jPad(jRow([jLabel("Name"),oName],8),12),
		NULL,
		jPad(jButton("Hello","onHello"),8),
		NULL,
		NULL
	),"Center"])
jShow(oWin)
jMainLoop()

func onHello aArgs
	jMessage("Hello " + oName.getText(),"Hello")

A handler is the name of a Ring function that gets the Java event in aArgs (as in oButton.addActionListener("name")), or "" for none.

Windows and controls#

FunctionMeaning
jWindow(title, width, height)a JFrame, centred, that closes itself (not the program) when the user closes it; size 0 leaves the size to jPack()
jPack(oWindow), jShow(oWindow)fit the window to its contents; show it
jLabel(text)a label
jButton(text, handler)a button
jField(text, columns, handler)a text field; the handler runs on Enter
jTextArea(text, rows, columns)a text area (put it in jScroll())
jCheck(text, lOn, handler)a check box
jCombo(items, handler)a drop-down list of texts; the handler runs when the choice changes
jListBox(items)a list of texts
jSlider(min, max, value, handler)a slider; the handler runs when the value changes

Layouts#

FunctionMeaning
jRow(items, gap)side by side
jColumn(items, gap)one below the other, left aligned
jGrid(rows, cols, items, gap)equal cells; 0 rows or columns means as many as needed
jForm(pairs, gap)a list of [label text, control] in two columns
jBorder(center, north, south, west, east)the five areas of a window; NULL for an area that is not used
jPad(item, size)space around a control
jTitled(item, title)a border with a title
jScroll(item)scroll bars

jMenuBar(oWindow, menus) makes the menu bar from a list of [title, items]. An item is [text, handler] or [text, handler, shortcut] ("ctrl O"), and "-" is a separator:

Ring
jMenuBar(oWin,[
	["File",[
		["Open","onOpen","ctrl O"],
		"-",
		["Exit","onExit"]
	]]
])

jOpenFile(title) and jSaveFile(title) give the path chosen by the user (or ""), and jChooseColor(title, colour) a Java Color (or NULL). jMessage, jConfirm and jInput are in Windows and events.

Colours#

Wherever a colour is wanted you can give a Java Color, [r,g,b], [r,g,b,a], "#rrggbb" or a name: red, green, blue, black, white, gray, yellow, orange, pink, cyan, magenta.

JCanvas: a surface to draw on#

new JCanvas(width, height) is a picture (a BufferedImage with anti-aliasing) shown in a label. Draw with the methods below, call update() to show the result, and add component() to a window. Every method gives the canvas back, so calls can be chained: oCanvas.color("red").fillRect(10,10,50,20).

MethodMeaning
color(c), lineWidth(n), font(name, size, lBold)the state of the drawing
clear(c)fill the surface (the drawing colour is kept)
line(x1,y1,x2,y2), rect(x,y,w,h), fillRect(...), oval(...), fillOval(...)shapes
text(text, x, y)a text with its base line at y
arc, fillArc, roundRect, fillRoundRect, polygon, fillPolygon, polyline, textWidth, textHeightmore shapes and the size of a text (see Charts and drawing)
pixel(x, y)the colour of a point as a number (0xRRGGBB)
setPixel(x, y, red, green, blue)one pixel (parts 0 to 255): a call into Java for each pixel, about 30 microseconds
setPixels(x, y, w, h, rgb)a rectangle of pixels from one text of 3 bytes for each pixel, row after row, in one call (see below)
getPixels(x, y, w, h)a rectangle of pixels as the same kind of text
loadImage(file), drawImage(picture, x, y, width, height)load a picture file (png, jpg, gif, bmp) once, then draw it scaled to a rectangle
update()show what has been drawn
save(file)save the picture; the extension is the format (png, jpg, bmp, gif)
onPress(h), onRelease(h), onMove(h), onDrag(h)mouse handlers: a Ring function func name nX, nY with the position in the picture
component(), width(), height(), finish()the control; the size; release the drawing resources

Drawing pixel by pixel#

For a picture that a formula makes (a fractal, a colour wheel, a plasma), let Ring compute the colour of every pixel and give them all to setPixels in one call. A call from Ring into Java costs some microseconds, so setPixel for each pixel is slow: about 30 microseconds each, which is 2.3 seconds for a picture of 320 x 240 pixels. One text of 3 bytes for each pixel (char(red) + char(green) + char(blue), row after row) goes to Java as it is and is copied into the picture in a single step: about 8 milliseconds for the same picture, and most of that is the text itself.

Ring
cPixels = ""                                   # 3 bytes for each pixel, row after row
for nRow = 1 to nHeight
	for nCol = 1 to nWidth
		cPixels += char(nRed) + char(nGreen) + char(nBlue)       # the colour of the pixel nCol, nRow
	next
next
oCanvas.setPixels(0,0,nWidth,nHeight,cPixels)     # the whole picture, one call
oCanvas.update()

Make the colour of a pixel as a text, not as a list (a list for each pixel is the slowest part of a Ring program), and look up a table (aPalette[n] holds the 3 bytes of a colour) instead of computing the colour again. The plasma sample does this: 76,800 pixels, 24 pictures a second, 24 ms of Ring and 1 ms of Java for each picture.

Samples#

samples/UsingJava/gui/11_builders.ring is an order form built with jForm, jColumn, jBorder and a menu; 12_canvas.ring is a small paint program with JCanvas.

samples/UsingJava/gui/11_builders.ring
samples/UsingJava/gui/11_builders.ring
# A window built with the helpers of RingJava: no layout code, no classes to import
load "java.ring"

oWin = jWindow("Order",420,300)

oName = jField("",16,"")
oSize = jCombo(["Small","Medium","Large"],"onChange")
oExtra = jCheck("Extra cheese",false,"onChange")
oQuantity = jSlider(1,10,1,"onChange")
oSummary = jLabel("")

oForm = jForm([
	["Name",oName],
	["Size",oSize],
	["",oExtra],
	["Quantity",oQuantity]
],8)

oButtons = jRow([
	jButton("Order","onOrder"),
	jButton("Clear","onClear")
],8)

oWin.add([jBorder(
		jPad(jColumn([oForm,oSummary],12),12),
		NULL,
		jPad(oButtons,8),
		NULL,
		NULL
	),"Center"])

jMenuBar(oWin,[
	["File",[
		["Order","onOrder","ctrl O"],
		"-",
		["Close","onClose"]
	]]
])

onChange([])
jShow(oWin)
jAutoClose()
jMainLoop()

func onChange aArgs
	aPrices = [8,10,12]
	nPrice = aPrices[oSize.getSelectedIndex() + 1]
	if oExtra.isSelected()
		nPrice += 2
	ok
	nCount = oQuantity.getValue()
	oSummary.setText(string(nCount) + " x " + oSize.getSelectedItem() + " = " + string(nPrice * nCount))

func onOrder aArgs
	if oName.getText() = ""
		jMessage("Please type a name","Order")
		return
	ok
	jMessage("Thank you " + oName.getText() + ": " + oSummary.getText(),"Order")

func onClear aArgs
	oName.setText("")
	oQuantity.setValue(1)
	oExtra.setSelected(false)
	oSize.setSelectedIndex(0)

func onClose aArgs
	jStopLoop()
samples/UsingJava/gui/12_canvas.ring
samples/UsingJava/gui/12_canvas.ring
# A small paint program with JCanvas: drag the mouse to draw, the buttons change the colour
load "java.ring"

oWin = jWindow("Paint",520,420)
oCanvas = new JCanvas(500,340)
oCanvas.lineWidth(4)
oCanvas.text("Drag the mouse here",20,30)
oCanvas.update()
nLastX = -1
nLastY = -1

aColours = ["black","red","green","blue","orange"]
aButtons = []
for cColour in aColours
	aButtons + jButton(cColour,"onColour")
next
aButtons + jButton("Clear","onClear")

oWin.add([jBorder(jScroll(oCanvas.component()),jPad(jRow(aButtons,6),6),NULL,NULL,NULL),"Center"])

oCanvas.onPress("onPress")
oCanvas.onDrag("onDrag")
oCanvas.onRelease("onRelease")
jShow(oWin)
jAutoClose()
jMainLoop()

func onColour aArgs
	oCanvas.color(aArgs[1].getActionCommand())

func onClear aArgs
	oCanvas.clear("white")
	oCanvas.update()

func onPress nX, nY
	nLastX = nX
	nLastY = nY
	oCanvas.fillOval(nX - 2,nY - 2,4,4)
	oCanvas.update()

func onDrag nX, nY
	oCanvas.line(nLastX,nLastY,nX,nY)
	nLastX = nX
	nLastY = nY
	oCanvas.update()

func onRelease nX, nY
	nLastX = -1

Pictures made pixel by pixel#

13_color_wheel.ring, 14_mandelbrot.ring (click the picture to zoom in) and 15_plasma.ring (an animation) draw with setPixels. The colour wheel (90,000 pixels) takes about 0.3 seconds of Ring and 10 milliseconds of Java; the Mandelbrot set (480 x 320, with the main cardioid skipped) about 0.6 seconds and 13 milliseconds.

samples/UsingJava/gui/13_color_wheel.ring
samples/UsingJava/gui/13_color_wheel.ring
# A color wheel drawn pixel by pixel: the hue of a pixel is its angle around the center, the saturation is its distance from it.
# A call from Ring into Java costs some microseconds, so the picture is not drawn with one call for each pixel: Ring computes the color of every pixel
# (a text of 3 bytes for each pixel) and JCanvas.setPixels() gives the whole picture to Java in one call.
load "java.ring"

nSize = 300                    # the picture is nSize x nSize pixels
nRadius = nSize / 2
nPi = 3.14159265359
nComputeTime = 0
nDrawTime = 0

oWin = jWindow("Color wheel",nSize + 40,nSize + 110)
oCanvas = new JCanvas(nSize,nSize)
oStatus = jLabel(" ")
oDraw = jButton("Draw again","onDraw")
oWin.add([jBorder(oCanvas.component(),NULL,jPad(jColumn([oDraw,oStatus],6),8),NULL,NULL),"Center"])
jShow(oWin)
onDraw(NULL)
jAutoClose()
jMainLoop()

# The button: compute the color of every pixel, then draw them all in one call
func onDraw aArgs
	oCanvas.clear("white")
	nStart = java_now()
	cPixels = computeWheel()
	nComputeTime = java_now() - nStart
	nStart = java_now()
	oCanvas.setPixels(0,0,nSize,nSize,cPixels)
	oCanvas.update()
	nDrawTime = java_now() - nStart
	oStatus.setText("Computed in " + floor(nComputeTime) + " ms, drawn in " + floor(nDrawTime) + " ms")

# The colors of the pixels, row after row. A pixel outside of the wheel is white.
func computeWheel
	cPixels = ""
	cWhite = char(255) + char(255) + char(255)
	for nRow = 1 to nSize
		nY = nRow - nRadius
		nYSquared = nY * nY
		cLine = ""
		for nCol = 1 to nSize
			nX = nCol - nRadius
			nSaturation = sqrt(nX * nX + nYSquared) / nRadius
			if nSaturation <= 1
				nHue = (atan2(nX,nY) + nPi) / (2 * nPi)
				cLine += hsvToBytes(nHue,nSaturation)
			else
				cLine += cWhite
			ok
		next
		cPixels += cLine
	next
	return cPixels

# The color of a hue and a saturation (0 to 1) at full brightness, as the 3 bytes red, green, blue (a text, not a list: no list is made for each pixel)
func hsvToBytes nHue, nSaturation
	nSector = floor(nHue * 6)
	nFraction = nHue * 6 - nSector
	nP = floor((1 - nSaturation) * 255 + 0.5)
	nQ = floor((1 - nSaturation * nFraction) * 255 + 0.5)
	nT = floor((1 - nSaturation * (1 - nFraction)) * 255 + 0.5)
	switch nSector % 6
	on 0
		return char(255) + char(nT) + char(nP)
	on 1
		return char(nQ) + char(255) + char(nP)
	on 2
		return char(nP) + char(255) + char(nT)
	on 3
		return char(nP) + char(nQ) + char(255)
	on 4
		return char(nT) + char(nP) + char(255)
	off
	return char(255) + char(nP) + char(nQ)
samples/UsingJava/gui/14_mandelbrot.ring
samples/UsingJava/gui/14_mandelbrot.ring
# The Mandelbrot set: each pixel is a point c of the complex plane, and its color is the number of steps that z = z * z + c takes to leave the circle of
# radius 2 (black for a point that never does). Click the picture to zoom in on that point; the button goes back to the whole set.
# The colors are computed in Ring, then JCanvas.setPixels() draws the whole picture in one call.
load "java.ring"

nWidth = 480                   # the picture is nWidth x nHeight pixels
nHeight = 320
nCenterX = -0.7                # the point at the center of the picture and the width of the part of the plane that it shows
nCenterY = 0
nSpan = 3.4
nMaxSteps = 80                 # a point that has not left the circle after this many steps is in the set
aPalette = []                  # the 3 bytes (red, green, blue) of each number of steps

oWin = jWindow("Mandelbrot",nWidth + 40,nHeight + 120)
oCanvas = new JCanvas(nWidth,nHeight)
oStatus = jLabel(" ")
oReset = jButton("Whole set","onReset")
oWin.add([jBorder(oCanvas.component(),NULL,jPad(jColumn([oReset,oStatus],6),8),NULL,NULL),"Center"])
oCanvas.onPress("onClick")
makePalette()
jShow(oWin)
draw()
jAutoClose()
jMainLoop()

func onReset aArgs
	nCenterX = -0.7
	nCenterY = 0
	nSpan = 3.4
	draw()

# A click: the point under the mouse becomes the center, and the picture shows a third of the width
func onClick nX, nY
	nCenterX = nCenterX + (nX - nWidth / 2) * nSpan / nWidth
	nCenterY = nCenterY - (nY - nHeight / 2) * nSpan / nWidth
	nSpan = nSpan / 3
	draw()

func draw
	nMaxSteps = 80 + floor(30 * log(3.4 / nSpan))      # a deeper view needs more steps
	makePalette()
	nStart = java_now()
	cPixels = computeMandelbrot()
	nComputeTime = java_now() - nStart
	nStart = java_now()
	oCanvas.setPixels(0,0,nWidth,nHeight,cPixels)
	oCanvas.update()
	nDrawTime = java_now() - nStart
	oStatus.setText("Computed in " + floor(nComputeTime) + " ms, drawn in " + floor(nDrawTime) + " ms (width " + nSpan + ")")

# The colors of the pixels, row after row
func computeMandelbrot
	cPixels = ""
	nStep = nSpan / nWidth
	nLeft = nCenterX - nSpan / 2
	nTop = nCenterY + nStep * nHeight / 2
	cBlack = char(0) + char(0) + char(0)
	for nRow = 1 to nHeight
		nY = nTop - (nRow - 0.5) * nStep
		nYSquared = nY * nY
		cLine = ""
		for nCol = 1 to nWidth
			nX = nLeft + (nCol - 0.5) * nStep
			# the main cardioid and the disc on its left are in the set: they need no steps (most of the work of the picture would be there)
			nQ = (nX - 0.25) * (nX - 0.25) + nYSquared
			if nQ * (nQ + (nX - 0.25)) < 0.25 * nYSquared or (nX + 1) * (nX + 1) + nYSquared < 0.0625
				nSteps = nMaxSteps
			else
				nSteps = escapeSteps(nX,nY)
			ok
			if nSteps >= nMaxSteps
				cLine += cBlack
			else
				cLine += aPalette[nSteps + 1]
			ok
		next
		cPixels += cLine
	next
	return cPixels

# The number of steps of z = z * z + c before z leaves the circle of radius 2 (nMaxSteps when it does not)
func escapeSteps nCr, nCi
	nZr = 0
	nZi = 0
	for nStep = 0 to nMaxSteps - 1
		nZr2 = nZr * nZr
		nZi2 = nZi * nZi
		if nZr2 + nZi2 > 4
			return nStep
		ok
		nZi = 2 * nZr * nZi + nCi
		nZr = nZr2 - nZi2 + nCr
	next
	return nMaxSteps

# The colors for 0 to nMaxSteps - 1 steps: the hue goes round the color wheel as the number of steps grows
func makePalette
	aPalette = []
	for nSteps = 0 to nMaxSteps - 1
		nHue = (0.6 + nSteps * 0.035) % 1
		aPalette + hsvToBytes(nHue,0.85)
	next

# The color of a hue and a saturation (0 to 1) at full brightness, as the 3 bytes red, green, blue
func hsvToBytes nHue, nSaturation
	nSector = floor(nHue * 6)
	nFraction = nHue * 6 - nSector
	nP = floor((1 - nSaturation) * 255 + 0.5)
	nQ = floor((1 - nSaturation * nFraction) * 255 + 0.5)
	nT = floor((1 - nSaturation * (1 - nFraction)) * 255 + 0.5)
	switch nSector % 6
	on 0
		return char(255) + char(nT) + char(nP)
	on 1
		return char(nQ) + char(255) + char(nP)
	on 2
		return char(nP) + char(255) + char(nT)
	on 3
		return char(nP) + char(nQ) + char(255)
	on 4
		return char(nT) + char(nP) + char(255)
	off
	return char(255) + char(nP) + char(nQ)
samples/UsingJava/gui/15_plasma.ring
samples/UsingJava/gui/15_plasma.ring
# An animated plasma: a timer computes a new picture 25 times a second, and each picture goes to Java in one call (JCanvas.setPixels).
# Ring does the arithmetic; the palette (256 colors made once) turns a number into the 3 bytes of a color.
load "java.ring"

nWidth = 320                   # the picture is nWidth x nHeight pixels
nHeight = 240
nFrame = 0
lBusy = false
nPi = 3.14159265359
aPalette = []
aSine = []                     # the sine of a table index: the formula looks sines up instead of calling sin() for each pixel
aRowSine = []

oWin = jWindow("Plasma",nWidth + 40,nHeight + 90)
oCanvas = new JCanvas(nWidth,nHeight)
oStatus = jLabel(" ")
oWin.add([jBorder(oCanvas.component(),NULL,jPad(oStatus,8),NULL,NULL),"Center"])
makeTables()
jShow(oWin)
oTimer = jTimer(40,"onFrame")
oTimer.start()
jAutoClose()
jMainLoop()
oTimer.stop()

# The sine of the angle n (0 to 255 are the angles 0 to 2 pi), and 256 colors that go round the wheel
func makeTables
	aSine = list(256)
	for n = 1 to 256
		aSine[n] = floor(127.5 + 127.5 * sin((n - 1) * 2 * nPi / 256))
	next
	aPalette = list(256)
	for n = 0 to 255
		nHue = n / 256
		nSector = floor(nHue * 6)
		nFraction = nHue * 6 - nSector
		nQ = floor((1 - nFraction) * 255)
		nT = floor(nFraction * 255)
		switch nSector % 6
		on 0
			aPalette[n + 1] = char(255) + char(nT) + char(0)
		on 1
			aPalette[n + 1] = char(nQ) + char(255) + char(0)
		on 2
			aPalette[n + 1] = char(0) + char(255) + char(nT)
		on 3
			aPalette[n + 1] = char(0) + char(nQ) + char(255)
		on 4
			aPalette[n + 1] = char(nT) + char(0) + char(255)
		other
			aPalette[n + 1] = char(255) + char(0) + char(nQ)
		off
	next

# A frame that takes longer than the timer interval must not start another one inside itself (Java calls can run the next tick of the timer)
func onFrame aArgs
	if lBusy
		return
	ok
	lBusy = true
	nStart = java_now()
	nFrame++
	cPixels = ""
	nShift = nFrame * 3
	for nRow = 0 to nHeight - 1
		nRowValue = aSine[1 + (nRow * 3 + nShift) % 256] + aSine[1 + (nRow * 2 - nShift * 2 + 1024) % 256]
		cLine = ""
		for nCol = 0 to nWidth - 1
			nValue = nRowValue + aSine[1 + (nCol * 2 + nShift) % 256] + aSine[1 + ((nCol + nRow) * 2 + nShift) % 256]
			cLine += aPalette[1 + nValue % 256]
		next
		cPixels += cLine
	next
	nComputed = java_now()
	oCanvas.setPixels(0,0,nWidth,nHeight,cPixels)
	oCanvas.update()
	oStatus.setText("Frame " + nFrame + ": computed in " + floor(nComputed - nStart) + " ms, drawn in " + floor(java_now() - nComputed) + " ms")
	lBusy = false
RingJava - use Java classes and methods from Ring programs.