Swing samples
Twelve windows, each with a screenshot made by the program itself, its source and the command that runs it.
Run one with ring 01_hello_window.ring from samples/UsingJava/gui. The windows close by themselves when the variable RINGJAVA_AUTOCLOSE is set to a number of milliseconds. Click Source code on a card to read the program.

Hello window
A window with a label and a button (Swing). The button's listener is a Ring function.
ring samples/UsingJava/gui/01_hello_window.ringSource code
# A window with a label and a button (Swing). The button's listener is a Ring function.
load "java.ring"
using {
"javax.swing"
"java.awt"
}
nClicks = 0
oFrame = new JFrame("Hello from Ring")
oFrame.setDefaultCloseOperation(2) # DISPOSE_ON_CLOSE: jMainLoop() ends when the window is closed
oFrame.setSize([320,160])
oFrame.setLocationRelativeTo(NULL)
oLabel = new JLabel("Press the button")
oLabel.setHorizontalAlignment(0) # CENTER
oButton = new JButton("Click me")
oButton.addActionListener("onClick")
oFrame.add([oLabel,"Center"])
oFrame.add([oButton,"South"])
oFrame.setVisible(true)
jAutoClose()
jMainLoop()
? "clicks: " + nClicks
func onClick aArgs
nClicks++
oLabel.setText("Clicked " + nClicks + " time(s)")
Form
A form: text fields, a combo box, a check box, and message boxes
ring samples/UsingJava/gui/02_form.ringSource code
# A form: text fields, a combo box, a check box, and message boxes
load "java.ring"
using {
"javax.swing"
"java.awt"
"java.awt.event"
}
oFrame = new JFrame("Registration")
oFrame.setDefaultCloseOperation(2)
oPanel = new JPanel
oPanel.setLayout((new GridLayout).@New([5,2,6,6])) # rows, columns, gaps
oPanel.setBorder(jStatic("javax.swing.BorderFactory","createEmptyBorder",[12,12,12,12]))
oName = new JTextField
oEmail = new JTextField
oCountry = new JComboBox
for cCountry in ["Egypt","France","Japan","Brazil"]
oCountry.addItem(cCountry)
next
oNews = new JCheckBox("Send me the news")
oPanel.add(new JLabel("Name"))
oPanel.add(oName)
oPanel.add(new JLabel("Email"))
oPanel.add(oEmail)
oPanel.add(new JLabel("Country"))
oPanel.add(oCountry)
oPanel.add(new JLabel(""))
oPanel.add(oNews)
oSave = new JButton("Save")
oSave.addActionListener("onSave")
oPanel.add(new JLabel(""))
oPanel.add(oSave)
oFrame.add(oPanel)
oFrame.pack()
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
jAutoClose()
jMainLoop()
func onSave aArgs
cName = oName.getText()
if trim(cName) = ""
jMessage("Please write the name","Registration")
return
ok
cNews = "no"
if oNews.isSelected()
cNews = "yes"
ok
? "Saved: " + cName + ", " + oEmail.getText() + ", " + oCountry.getSelectedItem() + ", news: " + cNews
jMessage("Saved " + cName,"Registration")
Todo list
A to-do list: a JList with a model, add/remove buttons, and Enter in the text field
ring samples/UsingJava/gui/03_todo_list.ringSource code
# A to-do list: a JList with a model, add/remove buttons, and Enter in the text field
load "java.ring"
using {
"javax.swing"
"java.awt"
}
oFrame = new JFrame("To-do")
oFrame.setDefaultCloseOperation(2)
oFrame.setSize([360,320])
oFrame.setLocationRelativeTo(NULL)
oModel = new DefaultListModel
oList = new JList(oModel)
oField = new JTextField
oAdd = new JButton("Add")
oDel = new JButton("Remove selected")
oCount = new JLabel("0 items")
oField.addActionListener("onAdd") # Enter
oAdd.addActionListener("onAdd")
oDel.addActionListener("onRemove")
oTop = new JPanel
oTop.setLayout(new BorderLayout)
oTop.add([oField,"Center"])
oTop.add([oAdd,"East"])
oBottom = new JPanel
oBottom.setLayout(new BorderLayout)
oBottom.add([oDel,"West"])
oBottom.add([oCount,"East"])
oFrame.add([oTop,"North"])
oFrame.add([new JScrollPane(oList),"Center"])
oFrame.add([oBottom,"South"])
oFrame.setVisible(true)
# a few items at the start
for cItem in ["Learn Ring","Call Java from Ring","Make a window"]
oModel.addElement(cItem)
next
refresh()
jAutoClose()
jMainLoop()
func onAdd aArgs
cText = trim(oField.getText())
if cText != ""
oModel.addElement(cText)
oField.setText("")
refresh()
ok
func onRemove aArgs
nAt = oList.getSelectedIndex()
if nAt >= 0
oModel.remove(nAt)
refresh()
ok
func refresh
oCount.setText(string(oModel.getSize()) + " items")
Table
A table (JTable) with a model made from Ring data, and a button that sorts by a column
ring samples/UsingJava/gui/04_table.ringSource code
# A table (JTable) with a model made from Ring data, and a button that sorts by a column
load "java.ring"
using {
"javax.swing"
"javax.swing.table"
"java.awt"
}
aPeople = [
["Mahmoud","Egypt",45],
["Sakura","Japan",31],
["Luc","France",52],
["Ana","Brazil",27]
]
oModel = (new DefaultTableModel).@New([ jArray("java.lang.String",["Name","Country","Age"]) , 0 ])
for aRow in aPeople
oModel.addRow(jArray("java.lang.Object",aRow))
next
oTable = new JTable(oModel)
oTable.setAutoCreateRowSorter(true) # click a column header to sort
oFrame = new JFrame("People")
oFrame.setDefaultCloseOperation(2)
oFrame.add([new JScrollPane(oTable),"Center"])
oStatus = new JLabel("Select a row")
oFrame.add([oStatus,"South"])
oTable.getSelectionModel().addListSelectionListener("onSelect")
oFrame.setSize([420,220])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
jAutoClose()
jMainLoop()
func onSelect aArgs
nRow = oTable.getSelectedRow()
if nRow >= 0
oStatus.setText("Selected: " + oTable.getValueAt(nRow,0) + " (" + oTable.getValueAt(nRow,2) + ")")
ok
Clock
A clock: a Swing timer calls a Ring function every second
ring samples/UsingJava/gui/05_clock.ringSource code
# A clock: a Swing timer calls a Ring function every second
load "java.ring"
using {
"javax.swing"
"java.awt"
"java.time"
"java.time.format"
}
oFrame = new JFrame("Clock")
oFrame.setDefaultCloseOperation(2)
oLabel = new JLabel("--:--:--")
oLabel.setHorizontalAlignment(0)
oLabel.setFont((new Font).@New(["Monospaced",1,48]))
oFrame.add(oLabel)
oFrame.setSize([320,120])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
oFormat = jStatic("java.time.format.DateTimeFormatter","ofPattern",["HH:mm:ss"])
tick(NULL)
oTimer = jTimer(1000,"tick")
oTimer.start()
jAutoClose()
jMainLoop()
oTimer.stop()
func tick aArgs
oLabel.setText(jStatic("java.time.LocalTime","now",[]).format(oFormat))
Drawing
Drawing with Java2D into an image and showing it in a label
ring samples/UsingJava/gui/06_drawing.ringSource code
# Drawing with Java2D into an image and showing it in a label
load "java.ring"
using {
"javax.swing"
"java.awt"
"java.awt.image"
}
nW = 360
nH = 240
oImage = (new BufferedImage).@New([nW,nH,1]) # TYPE_INT_RGB
g = oImage.createGraphics()
g.setRenderingHint(jGetStatic("java.awt.RenderingHints","KEY_ANTIALIASING"),jGetStatic("java.awt.RenderingHints","VALUE_ANTIALIAS_ON"))
g.setColor(jColor(250,250,240))
g.fillRect(0,0,nW,nH)
for i = 0 to 11
g.setColor(jColor(30 + i * 18,100,230 - i * 15))
g.fillOval(20 + i * 22,30 + (i % 4) * 40,60,60)
next
g.setColor(jColor(40,40,40))
g.setFont((new Font).@New(["SansSerif",1,22]))
g.drawString("Java2D from Ring",90,200)
g.dispose()
oFrame = new JFrame("Drawing")
oFrame.setDefaultCloseOperation(2)
oFrame.add(new JLabel(new ImageIcon(oImage)))
oFrame.pack()
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
jAutoClose()
jMainLoop()
Dialogs
Dialogs: a message box, a question and an input box. They are modal: the Ring program waits in them, and its timers and events still run.
ring samples/UsingJava/gui/07_dialogs.ringSource code
# Dialogs: a message box, a question and an input box. They are modal: the Ring program waits in them, and its timers and events still run.
load "java.ring"
using {
"javax.swing"
}
# a timer closes the dialogs by itself when RINGJAVA_AUTOCLOSE is set (the automatic run of the samples)
oTimer = NULL
if sysget("RINGJAVA_AUTOCLOSE") != ""
oTimer = jTimer(700,"closeDialogs")
oTimer.start()
ok
jMessage("Hello from a Java dialog","Message")
? "message closed"
lYes = jConfirm("Do you like Ring and Java together?","Question")
? "answer: " + lYes
cName = jInput("What is your name?","Input")
? "name: '" + cName + "'"
if oTimer != NULL
oTimer.stop()
ok
func closeDialogs aArgs
aWindows = jStatic("java.awt.Window","getWindows",[]).toList()
for oWindow in aWindows
if oWindow.isShowing()
oWindow.dispose()
ok
next
Calculator
A calculator: a grid of buttons that share one listener; the event tells which button was pressed
ring samples/UsingJava/gui/08_calculator.ringSource code
# A calculator: a grid of buttons that share one listener; the event tells which button was pressed
load "java.ring"
using {
"javax.swing"
"java.awt"
}
cEntry = "" # the number being typed
nLeft = 0
cOperator = ""
lFresh = true
oFrame = new JFrame("Calculator")
oFrame.setDefaultCloseOperation(2)
oFrame.setLayout(new BorderLayout)
oDisplay = new JTextField("0")
oDisplay.setHorizontalAlignment(4) # RIGHT
oDisplay.setEditable(false)
oDisplay.setFont((new Font).@New(["Monospaced",1,26]))
oFrame.add([oDisplay,"North"])
oGrid = new JPanel
oGrid.setLayout((new GridLayout).@New([4,4,4,4]))
for cKey in ["7","8","9","/","4","5","6","*","1","2","3","-","0",".","=","+"]
oButton = new JButton(cKey)
oButton.setFont((new Font).@New(["SansSerif",1,20]))
oButton.addActionListener("onKey")
oGrid.add(oButton)
next
oFrame.add([oGrid,"Center"])
oClear = new JButton("C")
oClear.addActionListener("onKey")
oFrame.add([oClear,"South"])
oFrame.setSize([280,340])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
jAutoClose()
jMainLoop()
func onKey aArgs
cKey = aArgs[1].getActionCommand()
if cKey = "C"
cEntry = ""
nLeft = 0
cOperator = ""
show("0")
but isdigit(cKey) or cKey = "."
if lFresh
cEntry = ""
lFresh = false
ok
cEntry += cKey
show(cEntry)
else
if cEntry != ""
nRight = 0 + cEntry
if cOperator = ""
nLeft = nRight
else
nLeft = calculate(nLeft,cOperator,nRight)
ok
show(string(nLeft))
ok
cOperator = ""
if cKey != "="
cOperator = cKey
ok
cEntry = ""
lFresh = true
ok
func calculate nA, cOp, nB
switch cOp
on "+" return nA + nB
on "-" return nA - nB
on "*" return nA * nB
on "/" if nB = 0 return 0 ok return nA / nB
off
return nB
func show cText
oDisplay.setText(cText)
Editor
A text editor: a menu bar, a text area, and the file chooser. File > Open / Save use Java's file dialogs.
ring samples/UsingJava/gui/09_editor.ringSource code
# A text editor: a menu bar, a text area, and the file chooser. File > Open / Save use Java's file dialogs.
load "java.ring"
using {
"javax.swing"
"java.awt"
"java.io"
"java.nio.file"
}
cFile = ""
oFrame = new JFrame("Editor")
oFrame.setDefaultCloseOperation(2)
oArea = new JTextArea
oArea.setFont((new Font).@New(["Monospaced",0,14]))
oFrame.add([new JScrollPane(oArea),"Center"])
oStatus = new JLabel(" Ready")
oFrame.add([oStatus,"South"])
oBar = new JMenuBar
oFileMenu = new JMenu("File")
addItem(oFileMenu,"New","onNew")
addItem(oFileMenu,"Open...","onOpen")
addItem(oFileMenu,"Save","onSave")
oFileMenu.addSeparator()
addItem(oFileMenu,"Exit","onExit")
oBar.add(oFileMenu)
oEditMenu = new JMenu("Edit")
addItem(oEditMenu,"Count words","onCount")
oBar.add(oEditMenu)
oFrame.setJMenuBar(oBar)
oFrame.setSize([560,380])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
oArea.setText("Write here, then File > Save.")
jAutoClose()
jMainLoop()
func addItem oMenu, cText, cFunction
oItem = new JMenuItem(cText)
oItem.addActionListener(cFunction)
oMenu.add(oItem)
func onNew aArgs
oArea.setText("")
cFile = ""
oFrame.setTitle("Editor")
func onOpen aArgs
oChooser = new JFileChooser
if oChooser.showOpenDialog(oFrame) = 0
cFile = oChooser.getSelectedFile().getPath()
oArea.setText(jStatic("java.nio.file.Files","readString",[jStatic("java.nio.file.Path","of",[cFile])]))
oFrame.setTitle("Editor - " + cFile)
ok
func onSave aArgs
if cFile = ""
oChooser = new JFileChooser
if oChooser.showSaveDialog(oFrame) != 0
return
ok
cFile = oChooser.getSelectedFile().getPath()
ok
write(cFile,oArea.getText())
oStatus.setText(" Saved " + cFile)
oFrame.setTitle("Editor - " + cFile)
func onCount aArgs
nWords = len(str2list(substr(trim(substr(oArea.getText()," ",nl))," ",nl)))
jMessage("Words: " + nWords,"Count")
func onExit aArgs
oFrame.dispose()
Tree
A tree (JTree): the folders of a path, loaded when a node is expanded
ring samples/UsingJava/gui/10_tree.ringSource code
# A tree (JTree): the folders of a path, loaded when a node is expanded
load "java.ring"
using {
"javax.swing"
"javax.swing.tree"
"javax.swing.event"
"java.awt"
}
oRoot = new DefaultMutableTreeNode("Languages")
for aLanguage in [["Ring",["Ring 1.29","RingDotNet","RingJava"]],["Java",["JDK 25","Swing","JDBC"]],["C",["clang","gcc"]]]
oNode = new DefaultMutableTreeNode(aLanguage[1])
for cChild in aLanguage[2]
oNode.add(new DefaultMutableTreeNode(cChild))
next
oRoot.add(oNode)
next
oTree = new JTree(oRoot)
oTree.addTreeSelectionListener("onSelect")
for nRow = 0 to 2
oTree.expandRow(nRow)
next
oFrame = new JFrame("Tree")
oFrame.setDefaultCloseOperation(2)
oFrame.add([new JScrollPane(oTree),"Center"])
oInfo = new JLabel(" Select a node")
oFrame.add([oInfo,"South"])
oFrame.setSize([300,320])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
jAutoClose()
jMainLoop()
func onSelect aArgs
oNode = oTree.getLastSelectedPathComponent()
if not isnull(oNode)
oInfo.setText(" " + oNode.toString() + " (" + oNode.getChildCount() + " children)")
ok
Builders
A window built with the helpers of RingJava: no layout code, no classes to import
ring samples/UsingJava/gui/11_builders.ringSource code
# 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()
Canvas
A small paint program with JCanvas: drag the mouse to draw, the buttons change the colour
ring samples/UsingJava/gui/12_canvas.ringSource code
# 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
Color wheel
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.
ring samples/UsingJava/gui/13_color_wheel.ringSource code
# 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)
Mandelbrot
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.
ring samples/UsingJava/gui/14_mandelbrot.ringSource code
# 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)
Plasma
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.
ring samples/UsingJava/gui/15_plasma.ringSource code
# 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
Julia
A Julia set: the same formula as the Mandelbrot set, z = z * z + c, but c is fixed for the whole picture and z starts at the pixel. Press and drag the mouse over the small Mandelbrot picture (left) to choose c: the Julia set of that point is drawn on the right, in one setPixels() call.
ring samples/UsingJava/gui/16_julia.ringSource code
# A Julia set: the same formula as the Mandelbrot set, z = z * z + c, but c is fixed for the whole picture and z starts at the pixel.
# Press and drag the mouse over the small Mandelbrot picture (left) to choose c: the Julia set of that point is drawn on the right, in one setPixels() call.
load "java.ring"
nWidth = 240 # the size of each of the two pictures
nHeight = 180
nMaxSteps = 40
nCr = -0.8 # the point c
nCi = 0.156
lBusy = false
aPalette = []
oWin = jWindow("Julia set",nWidth * 2 + 50,nHeight + 100)
oMap = new JCanvas(nWidth,nHeight) # the Mandelbrot set: the places where c can be chosen
oJulia = new JCanvas(nWidth,nHeight)
oStatus = jLabel(" ")
oWin.add([jBorder(jRow([oMap.component(),oJulia.component()],10),NULL,jPad(oStatus,8),NULL,NULL),"Center"])
oMap.onPress("onChoose")
oMap.onDrag("onChoose")
makePalette()
oMap.setPixels(0,0,nWidth,nHeight,computeMap())
oMap.update()
jShow(oWin)
drawJulia()
jAutoClose()
jMainLoop()
# The mouse over the small picture: the point under it is c (x from -2.2 to 1, y from 1.2 to -1.2)
func onChoose nX, nY
if lBusy or nX < 0 or nY < 0 or nX >= nWidth or nY >= nHeight
return
ok
nCr = -2.2 + nX * 3.2 / nWidth
nCi = 1.2 - nY * 2.4 / nHeight
drawJulia()
func drawJulia
lBusy = true
nStart = java_now()
cPixels = computeJulia()
nComputeTime = java_now() - nStart
nStart = java_now()
oJulia.setPixels(0,0,nWidth,nHeight,cPixels)
oJulia.update()
oStatus.setText("c = " + floor(nCr * 1000) / 1000 + " + " + floor(nCi * 1000) / 1000 + "i: computed in " + floor(nComputeTime) + " ms, drawn in " + floor(java_now() - nStart) + " ms")
lBusy = false
# The colors of the Julia set of c, row after row: z starts at the point of the pixel (x from -1.6 to 1.6, y from 1.2 to -1.2)
func computeJulia
cPixels = ""
cBlack = char(0) + char(0) + char(0)
nStepX = 3.2 / nWidth
nStepY = 2.4 / nHeight
for nRow = 1 to nHeight
nY = 1.2 - (nRow - 0.5) * nStepY
cLine = ""
for nCol = 1 to nWidth
nZr = -1.6 + (nCol - 0.5) * nStepX
nZi = nY
nStep = 0
while nStep < nMaxSteps
nZr2 = nZr * nZr
nZi2 = nZi * nZi
if nZr2 + nZi2 > 4
exit
ok
nZi = 2 * nZr * nZi + nCi
nZr = nZr2 - nZi2 + nCr
nStep++
end
if nStep >= nMaxSteps
cLine += cBlack
else
cLine += aPalette[nStep + 1]
ok
next
cPixels += cLine
next
return cPixels
# The small Mandelbrot picture (the same colors, fewer steps)
func computeMap
cPixels = ""
cBlack = char(0) + char(0) + char(0)
nStepX = 3.2 / nWidth
nStepY = 2.4 / nHeight
for nRow = 1 to nHeight
nY = 1.2 - (nRow - 0.5) * nStepY
cLine = ""
for nCol = 1 to nWidth
nX = -2.2 + (nCol - 0.5) * nStepX
nZr = 0
nZi = 0
nStep = 0
while nStep < nMaxSteps
nZr2 = nZr * nZr
nZi2 = nZi * nZi
if nZr2 + nZi2 > 4
exit
ok
nZi = 2 * nZr * nZi + nY
nZr = nZr2 - nZi2 + nX
nStep++
end
if nStep >= nMaxSteps
cLine += cBlack
else
cLine += aPalette[nStep + 1]
ok
next
cPixels += cLine
next
return cPixels
func makePalette
aPalette = []
for nSteps = 0 to nMaxSteps - 1
nHue = (0.6 + nSteps * 0.035) % 1
nSector = floor(nHue * 6)
nFraction = nHue * 6 - nSector
nP = 38
nQ = floor((1 - 0.85 * nFraction) * 255 + 0.5)
nT = floor((1 - 0.85 * (1 - nFraction)) * 255 + 0.5)
switch nSector % 6
on 0
aPalette + (char(255) + char(nT) + char(nP))
on 1
aPalette + (char(nQ) + char(255) + char(nP))
on 2
aPalette + (char(nP) + char(255) + char(nT))
on 3
aPalette + (char(nP) + char(nQ) + char(255))
on 4
aPalette + (char(nT) + char(nP) + char(255))
other
aPalette + (char(255) + char(nP) + char(nQ))
off
next
Charts
JChart: a bar chart, a line chart, a scatter plot and a pie, one on each tab. The data are lists; JChart draws the axes, the grid and the legend.
ring samples/UsingJava/gui/17_charts.ringSource code
# JChart: a bar chart, a line chart, a scatter plot and a pie, one on each tab. The data are lists; JChart draws the axes, the grid and the legend.
load "java.ring"
aMonths = ["Jan","Feb","Mar","Apr","May","Jun"]
oBars = new JChart(520,320)
oBars.title("Sales by month").axisTitles("Month","Units").showValues(true)
oBars.bars(aMonths,[ ["2025",[120,150,90,180,210,160]], ["2026",[140,170,130,200,190,240]] ])
oLines = new JChart(520,320)
oLines.title("Temperature").axisTitles("Month","Degrees")
oLines.lines(aMonths,[ ["Cairo",[14,16,19,24,28,31]], ["London",[5,5,8,11,15,18]], ["Moscow",[-6,-5,0,8,15,19]] ])
aPoints = []
for n = 1 to 40
aPoints + [n / 4,sin(n / 4) * 3 + n / 5]
next
oScatter = new JChart(520,320)
oScatter.title("A sine wave and a slope")
oScatter.scatter([ ["sin(x) * 3 + x / 5",aPoints] ])
oPie = new JChart(520,320)
oPie.title("Where the time goes").showValues(true)
oPie.pie(["Work","Sleep","Meals","Travel","Free"],[8,7,2,1.5,5.5])
oWin = jWindow("Charts",560,400)
oTabs = new JTabbedPane
oTabs.addTab(["Bars",oBars.component()])
oTabs.addTab(["Lines",oLines.component()])
oTabs.addTab(["Scatter",oScatter.component()])
oTabs.addTab(["Pie",oPie.component()])
oWin.add([oTabs,"Center"])
jShow(oWin)
jAutoClose()
jMainLoop()