Gallery
Every window of the package in one place - the applications, the Swing samples, the windows of the tutorials and JavaFX - each with a screenshot made by the program itself.
Each card shows the picture, the command that runs the program and its source code (click Source code). Set the variable RINGJAVA_AUTOCLOSE to a number of milliseconds to make a window close by itself.
Applications#
Forty-seven complete programs in samples/UsingJava/applications. See Applications for what each one shows.

Address Book
Address book: a JTable showing the rows of an H2 database; add and delete contacts, search while typing.
cd samples/UsingJava/applications/AddressBook then ring AddressBook.ringSource code
# Address book: a JTable showing the rows of an H2 database; add and delete contacts, search while typing.
load "java.ring"
using {
"javax.swing"
"javax.swing.table"
"javax.swing.event"
"java.awt"
}
jMaven("com.h2database:h2:2.2.224")
oDb = jSqlConnect("jdbc:h2:mem:addressbook")
jSqlScript(oDb,"
create table contact (id int auto_increment primary key, name varchar(60), phone varchar(30), city varchar(40));
insert into contact (name, phone, city) values ('Mahmoud', '0100-111', 'Cairo');
insert into contact (name, phone, city) values ('Sara', '0111-222', 'Alexandria');
insert into contact (name, phone, city) values ('Omar', '0122-333', 'Giza');
insert into contact (name, phone, city) values ('Layla', '0155-444', 'Cairo');
")
oModel = (new DefaultTableModel).@New([jArray("java.lang.String",["ID","Name","Phone","City"]),0])
oTable = new JTable(oModel)
oTable.setAutoCreateRowSorter(true)
oSearch = new JTextField
oName = new JTextField
oPhone = new JTextField
oCity = new JTextField
oAdd = new JButton("Add")
oDelete = new JButton("Delete selected")
oStatus = new JLabel(" ")
oTop = new JPanel(new BorderLayout)
oTop.add([new JLabel(" Search: "),"West"])
oTop.add([oSearch,"Center"])
oForm = new JPanel((new GridLayout).@New([1,0,4,4]))
for oItem in [oName,oPhone,oCity,oAdd,oDelete]
oForm.add(oItem)
next
oSouth = new JPanel(new BorderLayout)
oSouth.add([oForm,"North"])
oSouth.add([oStatus,"South"])
oFrame = new JFrame("Address book")
oFrame.setDefaultCloseOperation(2)
oFrame.add([oTop,"North"])
oFrame.add([new JScrollPane(oTable),"Center"])
oFrame.add([oSouth,"South"])
oFrame.setSize([620,380])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
oSearch.getDocument().addDocumentListener("onSearch")
oAdd.addActionListener("onAdd")
oDelete.addActionListener("onDelete")
load_rows("")
jAutoClose()
jMainLoop()
oDb.close()
func load_rows cFilter
oModel.setRowCount(0)
cLike = "%" + lower(cFilter) + "%"
aRows = jSqlQuery(oDb,"select id, name, phone, city from contact where lower(name) like ? or lower(city) like ? order by name",[cLike,cLike])
for aRow in aRows
oModel.addRow(jArray("java.lang.Object",[aRow[:id],aRow[:name],aRow[:phone],aRow[:city]]))
next
oStatus.setText(" " + len(aRows) + " contacts")
func onSearch aArgs
load_rows(oSearch.getText())
func onAdd aArgs
cName = oName.getText()
if trim(cName) = ""
oStatus.setText(" The name is required")
return
ok
jSqlExec(oDb,"insert into contact (name, phone, city) values (?, ?, ?)",[cName,oPhone.getText(),oCity.getText()])
oName.setText("")
oPhone.setText("")
oCity.setText("")
load_rows(oSearch.getText())
func onDelete aArgs
nRow = oTable.getSelectedRow()
if nRow < 0
oStatus.setText(" Select a contact first")
return
ok
nId = oModel.getValueAt(oTable.convertRowIndexToModel(nRow),0)
jSqlExec(oDb,"delete from contact where id = ?",[nId])
load_rows(oSearch.getText())
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
aChecks + ["the contacts at the start",oModel.getRowCount(),4]
oSearch.setText("cairo")
aChecks + ["the search keeps the contacts of Cairo",oModel.getRowCount(),2]
oSearch.setText("")
oName.setText("Zed")
oCity.setText("Luxor")
oAdd.doClick()
aChecks + ["Add makes a row",oModel.getRowCount(),5]
oTable.setRowSelectionInterval(0,0)
oDelete.doClick()
aChecks + ["Delete removes the selected row",oModel.getRowCount(),4]
return aChecks
Analog Clock
An analog clock: a Swing timer draws the hands every second on a JCanvas.
cd samples/UsingJava/applications/AnalogClock then ring AnalogClock.ringSource code
# An analog clock: a Swing timer draws the hands every second on a JCanvas.
load "java.ring"
using {
"javax.swing"
}
C_CENTER = 150
C_PI = 3.14159265358979
oCanvas = new JCanvas(300,300)
oDigital = new JLabel("")
oDigital.setHorizontalAlignment(0)
oFrame = new JFrame("Analog clock")
oFrame.setDefaultCloseOperation(2)
oFrame.add([oCanvas.component(),"Center"])
oFrame.add([oDigital,"South"])
oFrame.pack()
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
oTimer = jTimer(1000,"tick")
tick(NULL)
oTimer.start()
jAutoClose()
jMainLoop()
oTimer.stop()
# the end of a hand: nAngle in degrees (0 = 12 o'clock, clockwise)
func handX nAngle, nLength
return floor(C_CENTER + nLength * sin(nAngle * C_PI / 180) + 0.5)
func handY nAngle, nLength
return floor(C_CENTER - nLength * cos(nAngle * C_PI / 180) + 0.5)
func drawClock nHour, nMinute, nSecond
oCanvas.clear("white")
oCanvas.color(jColor(244,241,232))
oCanvas.fillOval(C_CENTER - 140,C_CENTER - 140,280,280)
oCanvas.color("black")
oCanvas.lineWidth(2)
oCanvas.oval(C_CENTER - 140,C_CENTER - 140,280,280)
for nMark = 0 to 59
nAngle = nMark * 6
if nMark % 5 = 0
oCanvas.lineWidth(3)
oCanvas.color("black")
oCanvas.line(handX(nAngle,122),handY(nAngle,122),handX(nAngle,136),handY(nAngle,136))
else
oCanvas.lineWidth(1)
oCanvas.color("gray")
oCanvas.line(handX(nAngle,130),handY(nAngle,130),handX(nAngle,136),handY(nAngle,136))
ok
next
nHourAngle = (nHour % 12) * 30 + nMinute * 0.5
nMinuteAngle = nMinute * 6 + nSecond * 0.1
nSecondAngle = nSecond * 6
oCanvas.lineWidth(6)
oCanvas.color("black")
oCanvas.line(C_CENTER,C_CENTER,handX(nHourAngle,70),handY(nHourAngle,70))
oCanvas.lineWidth(4)
oCanvas.color("blue")
oCanvas.line(C_CENTER,C_CENTER,handX(nMinuteAngle,105),handY(nMinuteAngle,105))
oCanvas.lineWidth(2)
oCanvas.color("red")
oCanvas.line(C_CENTER,C_CENTER,handX(nSecondAngle,120),handY(nSecondAngle,120))
oCanvas.color("black")
oCanvas.fillOval(C_CENTER - 6,C_CENTER - 6,12,12)
oCanvas.update()
func twoDigits n
cText = "" + floor(n)
if len(cText) < 2
cText = "0" + cText
ok
return cText
func tick aArgs
oNow = jStatic("java.time.LocalTime","now",[])
showTime(oNow.getHour(),oNow.getMinute(),oNow.getSecond())
func showTime nHour, nMinute, nSecond
drawClock(nHour,nMinute,nSecond)
oDigital.setText(twoDigits(nHour) + ":" + twoDigits(nMinute) + ":" + twoDigits(nSecond))
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
aChecks + ["hand at 3 o'clock x",handX(90,100),250]
aChecks + ["hand at 3 o'clock y",handY(90,100),150]
aChecks + ["hand at 12 o'clock y",handY(0,100),50]
aChecks + ["two digits",twoDigits(7),"07"]
showTime(3,15,30)
aChecks + ["digital time",oDigital.getText(),"03:15:30"]
return aChecks
Ascii Table
ASCII table in a JTable with a filter that works while you type.
cd samples/UsingJava/applications/AsciiTable then ring AsciiTable.ringSource code
# ASCII table in a JTable with a filter that works while you type.
load "java.ring"
using {
"javax.swing"
"javax.swing.table"
"java.awt"
}
aNames = ["NUL","SOH","STX","ETX","EOT","ENQ","ACK","BEL","BS","TAB","LF","VT","FF","CR","SO","SI","DLE","DC1","DC2","DC3","DC4","NAK","SYN","ETB","CAN","EM","SUB","ESC","FS","GS","RS","US"]
oFrame = new JFrame("ASCII table")
oFrame.setDefaultCloseOperation(2)
oFilter = new JTextField("")
oFilter.getDocument().addDocumentListener("onFilter")
oCount = new JLabel(" ")
oTop = new JPanel(new BorderLayout)
oTop.add([new JLabel(" Filter: "),"West"])
oTop.add([oFilter,"Center"])
oTop.add([oCount,"East"])
oModel = (new DefaultTableModel).@New([jArray("java.lang.String",["Dec","Hex","Binary","Char"]),0])
oTable = new JTable(oModel)
oFrame.add([oTop,"North"])
oFrame.add([new JScrollPane(oTable),"Center"])
oFrame.setSize([460,560])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
fillTable()
jAutoClose()
jMainLoop()
func charName nCode
if nCode < 32
return aNames[nCode + 1]
but nCode = 32
return "SPACE"
but nCode = 127
return "DEL"
ok
return char(nCode)
func binary nCode
cBits = ""
for nBit = 7 to 0 step -1
if floor(nCode / pow(2,nBit)) % 2 = 1
cBits += "1"
else
cBits += "0"
ok
next
return cBits
func onFilter aArgs
fillTable()
func fillTable
cFilter = lower(oFilter.getText())
oModel.setRowCount(0)
nShown = 0
for nCode = 0 to 127
cName = charName(nCode)
cHex = upper(hex(nCode))
if len(cHex) = 1
cHex = "0" + cHex
ok
cRow = "" + nCode + " " + lower(cHex) + " " + lower(cName)
if cFilter = "" or substr(cRow,cFilter)
oModel.addRow(jArray("java.lang.Object",["" + nCode,cHex,binary(nCode),cName]))
nShown++
ok
next
oCount.setText(string(nShown) + " characters ")
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
aChecks + ["all the characters",oModel.getRowCount(),128]
aChecks + ["the binary text",binary(65),"01000001"]
aChecks + ["a control character",charName(10),"LF"]
aChecks + ["the space",charName(32),"SPACE"]
oFilter.setText("esc")
aChecks + ["a filter",oModel.getRowCount(),1]
aChecks + ["the filtered row",oModel.getValueAt(0,0),"27"]
oFilter.setText("4a")
aChecks + ["a filter on a hex number",oModel.getValueAt(0,3),"J"]
oFilter.setText("")
aChecks + ["no filter again",oModel.getRowCount(),128]
aChecks + ["the count label",trim(oCount.getText()),"128 characters"]
return aChecks
BMICalculator
BMI calculator with a history: metric or imperial units.
cd samples/UsingJava/applications/BMICalculator then ring BMICalculator.ringSource code
# BMI calculator with a history: metric or imperial units.
load "java.ring"
using {
"javax.swing"
"java.awt"
}
oFrame = new JFrame("BMI calculator")
oFrame.setDefaultCloseOperation(2)
oUnits = jCombo(["Metric (kg, cm)","Imperial (lb, in)"],"onUnits")
oWeightLabel = new JLabel("Weight (kg)")
oHeightLabel = new JLabel("Height (cm)")
oWeight = new JTextField("")
oHeight = new JTextField("")
oCalc = new JButton("Calculate")
oClear = new JButton("Clear history")
oCalc.addActionListener("onCalculate")
oClear.addActionListener("onClear")
oForm = new JPanel((new GridLayout).@New([4,2,8,8]))
oForm.add(new JLabel("Units"))
oForm.add(oUnits)
oForm.add(oWeightLabel)
oForm.add(oWeight)
oForm.add(oHeightLabel)
oForm.add(oHeight)
oForm.add(oCalc)
oForm.add(oClear)
oBmi = new JLabel(" ")
oBmi.setFont((new Font).@New(["SansSerif",1,18]))
oCategory = new JLabel(" ")
oHistory = new DefaultListModel
oList = new JList(oHistory)
oResults = new JPanel((new GridLayout).@New([2,1,0,0]))
oResults.add(oBmi)
oResults.add(oCategory)
oTop = new JPanel(new BorderLayout)
oTop.setBorder(jStatic("javax.swing.BorderFactory","createEmptyBorder",[10,10,10,10]))
oTop.add([oForm,"North"])
oTop.add([oResults,"Center"])
oFrame.add([oTop,"North"])
oFrame.add([new JScrollPane(oList),"Center"])
oFrame.setSize([360,420])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
jAutoClose()
jMainLoop()
# a number with one decimal: 22.9, and 31.0 not 31
func oneDecimal nValue
nTenths = floor(nValue * 10 + 0.5)
return "" + floor(nTenths / 10) + "." + floor(nTenths % 10)
func bmi nKilograms, nMeters
return nKilograms / (nMeters * nMeters)
func category nBmi
if nBmi < 18.5
return "Underweight"
but nBmi < 25
return "Normal weight"
but nBmi < 30
return "Overweight"
ok
return "Obese"
func onUnits aArgs
if oUnits.getSelectedIndex() = 0
oWeightLabel.setText("Weight (kg)")
oHeightLabel.setText("Height (cm)")
else
oWeightLabel.setText("Weight (lb)")
oHeightLabel.setText("Height (in)")
ok
func onClear aArgs
oHistory.clear()
func onCalculate aArgs
nWeight = number(oWeight.getText())
nHeight = number(oHeight.getText())
if nWeight <= 0 or nHeight <= 0
oBmi.setText("Enter a weight and a height")
oCategory.setText(" ")
return
but oUnits.getSelectedIndex() = 0
nKilograms = nWeight
nMeters = nHeight / 100
else
nKilograms = nWeight * 0.45359237
nMeters = nHeight * 0.0254
ok
nValue = bmi(nKilograms,nMeters)
oBmi.setText("BMI " + oneDecimal(nValue))
oCategory.setText(category(nValue))
oHistory.insertElementAt(oBmi.getText() + " - " + oCategory.getText(),0)
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
oWeight.setText("70")
oHeight.setText("175")
oCalc.doClick()
aChecks + ["70 kg, 175 cm",oBmi.getText(),"BMI 22.9"]
aChecks + ["the category",oCategory.getText(),"Normal weight"]
oUnits.setSelectedIndex(1)
aChecks + ["imperial labels",oWeightLabel.getText(),"Weight (lb)"]
oWeight.setText("220")
oHeight.setText("70")
oCalc.doClick()
aChecks + ["220 lb, 70 in",oBmi.getText(),"BMI 31.6"]
aChecks + ["obese",oCategory.getText(),"Obese"]
aChecks + ["two lines in the history",oHistory.getSize(),2]
aChecks + ["the newest line is first",left(oHistory.getElementAt(0),8),"BMI 31.6"]
aChecks + ["underweight",category(17),"Underweight"]
aChecks + ["overweight",category(27),"Overweight"]
oWeight.setText("")
oCalc.doClick()
aChecks + ["empty input",oBmi.getText(),"Enter a weight and a height"]
oClear.doClick()
aChecks + ["clear history",oHistory.getSize(),0]
return aChecks
Calculator
Calculator: buttons and the keyboard (digits, + - * /, Enter, Escape, Backspace).
cd samples/UsingJava/applications/Calculator then ring Calculator.ringSource code
# Calculator: buttons and the keyboard (digits, + - * /, Enter, Escape, Backspace).
load "java.ring"
using {
"javax.swing"
"java.awt"
"java.awt.event"
}
cDisplay = "0" # the number being typed or the result
nAccumulator = 0 # the left operand
cOperator = "" # + - * /
lFresh = true # the next digit starts a new number
cHistory = ""
oFrame = new JFrame("Calculator")
oFrame.setDefaultCloseOperation(2)
oHistory = new JLabel(" ")
oHistory.setHorizontalAlignment(4)
oHistory.setForeground(jColor(120,120,120))
oScreen = new JTextField("0")
oScreen.setEditable(false)
oScreen.setHorizontalAlignment(4)
oScreen.setFont((new Font).@New(["SansSerif",0,26]))
oTop = new JPanel((new GridLayout).@New([2,1,0,2]))
oTop.add(oHistory)
oTop.add(oScreen)
oKeys = new JPanel((new GridLayout).@New([5,4,4,4]))
aKeys = ["C","+/-","%","/", "7","8","9","*", "4","5","6","-", "1","2","3","+", "0",".","sqrt","="]
for cKey in aKeys
oButton = new JButton(cKey)
oButton.setFocusable(false)
oButton.setFont((new Font).@New(["SansSerif",0,16]))
oButton.setActionCommand(cKey)
oButton.addActionListener("onButton")
if find(["/","*","-","+","="],cKey) > 0
oButton.setBackground(jColor(176,196,222))
ok
oKeys.add(oButton)
next
oPanel = new JPanel(new BorderLayout)
oPanel.setBorder(jStatic("javax.swing.BorderFactory","createEmptyBorder",[8,8,8,8]))
oPanel.add([oTop,"North"])
oPanel.add([oKeys,"Center"])
oFrame.add([oPanel,"Center"])
oFrame.setSize([300,400])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
oScreen.addKeyListener("onKey")
oScreen.requestFocus()
jAutoClose()
jMainLoop()
func onButton aArgs
press(aArgs[1].getActionCommand())
# the text of a number: 4 not 4.0
func formatNumber nValue
cText = string(nValue)
if substr(cText,".")
while right(cText,1) = "0"
cText = left(cText,len(cText) - 1)
end
if right(cText,1) = "."
cText = left(cText,len(cText) - 1)
ok
ok
return cText
func onKey aArgs
oEvent = aArgs[1]
if cJavaMethod = "keyTyped"
xChar = oEvent.getKeyChar()
if isnumber(xChar)
xChar = char(xChar)
ok
if find(["0","1","2","3","4","5","6","7","8","9",".","+","-","*","/","%"],xChar) > 0
press(xChar)
but xChar = "=" or xChar = char(10)
press("=")
but xChar = "c" or xChar = "C"
press("C")
ok
but cJavaMethod = "keyPressed"
nCode = oEvent.getKeyCode()
if nCode = 27
press("C")
but nCode = 8
backspace()
ok
ok
func backspace
if not lFresh and len(cDisplay) > 0
cDisplay = left(cDisplay,len(cDisplay) - 1)
if cDisplay = "" or cDisplay = "-"
cDisplay = "0"
lFresh = true
ok
oScreen.setText(cDisplay)
ok
func press cKey
if find(["0","1","2","3","4","5","6","7","8","9"],cKey) > 0
if lFresh
cDisplay = cKey
lFresh = false
but len(cDisplay) < 16
if cDisplay = "0"
cDisplay = cKey
else
cDisplay += cKey
ok
ok
but cKey = "."
if lFresh
cDisplay = "0."
lFresh = false
but not substr(cDisplay,".")
cDisplay += "."
ok
but cKey = "C"
cDisplay = "0"
nAccumulator = 0
cOperator = ""
lFresh = true
cHistory = ""
but cKey = "+/-"
if cDisplay != "0"
if left(cDisplay,1) = "-"
cDisplay = substr(cDisplay,2)
else
cDisplay = "-" + cDisplay
ok
ok
but cKey = "%"
cDisplay = formatNumber(number(cDisplay) / 100)
lFresh = true
but cKey = "sqrt"
if number(cDisplay) < 0
cDisplay = "Error"
else
cDisplay = formatNumber(sqrt(number(cDisplay)))
ok
lFresh = true
but find(["+","-","*","/"],cKey) > 0
if cOperator != "" and not lFresh
calculate()
ok
nAccumulator = number(cDisplay)
cOperator = cKey
cHistory = cDisplay + " " + cKey
lFresh = true
but cKey = "="
if cOperator != ""
cHistory = formatNumber(nAccumulator) + " " + cOperator + " " + cDisplay + " ="
calculate()
cOperator = ""
ok
ok
oScreen.setText(cDisplay)
oHistory.setText(" " + cHistory)
func calculate
nRight = number(cDisplay)
switch cOperator
on "+"
nResult = nAccumulator + nRight
on "-"
nResult = nAccumulator - nRight
on "*"
nResult = nAccumulator * nRight
on "/"
if nRight = 0
cDisplay = "Cannot divide by zero"
lFresh = true
nAccumulator = 0
cOperator = ""
return
ok
nResult = nAccumulator / nRight
off
cDisplay = formatNumber(nResult)
nAccumulator = nResult
lFresh = true
func typeKeys cKeys
for x = 1 to len(cKeys)
press(cKeys[x])
next
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
press("C")
oScreen.dispatchEvent(jNew("java.awt.event.KeyEvent",[oScreen,400,0,0,0,"7"])) # the keyboard works too
aChecks + ["a typed key",cDisplay,"7"]
press("C")
typeKeys("12+30=")
aChecks + ["12 + 30",cDisplay,"42"]
aChecks + ["the screen shows it",oScreen.getText(),"42"]
press("C")
typeKeys("7/2=")
aChecks + ["7 / 2",cDisplay,"3.5"]
press("C")
typeKeys("5/0=")
aChecks + ["division by zero",cDisplay,"Cannot divide by zero"]
press("C")
typeKeys("2+3*4=")
aChecks + ["left to right: (2 + 3) * 4",cDisplay,"20"]
press("C")
typeKeys("81")
press("sqrt")
aChecks + ["square root",cDisplay,"9"]
press("+/-")
aChecks + ["change of sign",cDisplay,"-9"]
press("C")
typeKeys("50")
press("%")
aChecks + ["percent",cDisplay,"0.5"]
press("C")
typeKeys("1.5.2")
aChecks + ["one decimal point",cDisplay,"1.52"]
backspace()
aChecks + ["backspace",cDisplay,"1.5"]
press("C")
typeKeys("9-4=")
aChecks + ["the history line",trim(oHistory.getText()),"9 - 4 ="]
return aChecks
Calendar
A calendar with date facts: a month grid of buttons; the facts come from the Java date classes (java.time).
cd samples/UsingJava/applications/Calendar then ring Calendar.ringSource code
# A calendar with date facts: a month grid of buttons; the facts come from the Java date classes (java.time).
load "java.ring"
using {
"javax.swing"
"java.awt"
}
aMonths = ["January","February","March","April","May","June","July","August","September","October","November","December"]
aDays = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
oToday = jStatic("java.time.LocalDate","now",[])
nYear = oToday.getYear()
nMonth = oToday.getMonthValue()
nDay = oToday.getDayOfMonth()
aDayButtons = []
oFrame = new JFrame("Calendar")
oFrame.setDefaultCloseOperation(2)
oPrev = new JButton("<")
oNext = new JButton(">")
oPrev.addActionListener("onPrev")
oNext.addActionListener("onNext")
oTitle = new JLabel("")
oTitle.setHorizontalAlignment(0)
oHead = new JPanel(new BorderLayout)
oHead.add([oPrev,"West"])
oHead.add([oTitle,"Center"])
oHead.add([oNext,"East"])
oGrid = new JPanel((new GridLayout).@New([7,7,2,2]))
for cName in ["Mo","Tu","We","Th","Fr","Sa","Su"]
oLabel = new JLabel(cName)
oLabel.setHorizontalAlignment(0)
oGrid.add(oLabel)
next
for nCell = 1 to 42
oButton = new JButton("")
oButton.setMargin((new Insets).@New([2,2,2,2]))
oButton.addActionListener("onDay")
aDayButtons + oButton
oGrid.add(oButton)
next
oLeft = new JPanel(new BorderLayout)
oLeft.add([oHead,"North"])
oLeft.add([oGrid,"Center"])
oLeft.setBorder(jStatic("javax.swing.BorderFactory","createEmptyBorder",[8,8,8,8]))
oFacts = new JLabel("")
oFacts.setVerticalAlignment(1)
oFacts.setPreferredSize((new Dimension).@New([230,260]))
oFrame.add([oLeft,"Center"])
oFrame.add([oFacts,"East"])
oFrame.setSize([560,300])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
showMonth()
jAutoClose()
jMainLoop()
func dateOf nY, nM, nD
return jStatic("java.time.LocalDate","of",[nY,nM,nD])
# the lines of facts about a date
func factsOf nY, nM, nD
oDate = dateOf(nY,nM,nD)
nDayOfYear = oDate.getDayOfYear()
nYearLength = oDate.lengthOfYear()
oField = jGetStatic("java.time.temporal.IsoFields","WEEK_OF_WEEK_BASED_YEAR")
cLeap = "no"
if oDate.isLeapYear()
cLeap = "yes"
ok
cText = "<html><b>" + aDays[oDate.getDayOfWeek().getValue()] + ", " + aMonths[nM] + " " + nD + ", " + nY + "</b><br><br>"
cText += "Day of the year: " + nDayOfYear + "<br>"
cText += "ISO week: " + oDate.@get(oField) + "<br>"
cText += "Days left in the year: " + (nYearLength - nDayOfYear) + "<br>"
cText += "Leap year: " + cLeap + "<br>"
cText += "Days in the month: " + oDate.lengthOfMonth() + "<br>"
cText += "Quarter: " + (floor((nM - 1) / 3) + 1) + "</html>"
return cText
func showMonth
oFirst = dateOf(nYear,nMonth,1)
nStart = oFirst.getDayOfWeek().getValue() # 1 = Monday
nLength = oFirst.lengthOfMonth()
if nDay > nLength
nDay = nLength
ok
for nCell = 1 to 42
nShown = nCell - nStart + 1
if nShown >= 1 and nShown <= nLength
aDayButtons[nCell].setText("" + nShown)
aDayButtons[nCell].setEnabled(true)
if nShown = nDay
aDayButtons[nCell].setBackground(jColor(150,190,255))
else
aDayButtons[nCell].setBackground(jColor(255,255,255))
ok
else
aDayButtons[nCell].setText("")
aDayButtons[nCell].setEnabled(false)
aDayButtons[nCell].setBackground(jColor(238,238,238))
ok
next
oTitle.setText(aMonths[nMonth] + " " + nYear)
oFacts.setText(factsOf(nYear,nMonth,nDay))
func moveMonth nStep
nMonth += nStep
if nMonth < 1
nMonth = 12
nYear--
but nMonth > 12
nMonth = 1
nYear++
ok
showMonth()
func onPrev aArgs
moveMonth(-1)
func onNext aArgs
moveMonth(1)
func onDay aArgs
cText = aArgs[1].getActionCommand()
if cText != ""
nDay = 0 + cText
showMonth()
ok
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
nYear = 2024
nMonth = 2
nDay = 29
showMonth()
aChecks + ["the title",oTitle.getText(),"February 2024"]
aChecks + ["Feb 1 2024 is a Thursday: the 4th cell",aDayButtons[4].getText(),"1"]
aChecks + ["the 29th is the last day",aDayButtons[32].getText(),"29"]
aChecks + ["the facts: weekday",substr(oFacts.getText(),"Thursday, February 29, 2024") > 0,true]
aChecks + ["the facts: day of the year",substr(oFacts.getText(),"Day of the year: 60") > 0,true]
aChecks + ["the facts: leap year",substr(oFacts.getText(),"Leap year: yes") > 0,true]
aChecks + ["the facts: ISO week",substr(oFacts.getText(),"ISO week: 9") > 0,true]
oNext.doClick()
aChecks + ["next month",oTitle.getText(),"March 2024"]
oPrev.doClick()
oPrev.doClick()
oPrev.doClick()
oPrev.doClick()
aChecks + ["back over the new year",oTitle.getText(),"November 2023"]
aDayButtons[10].doClick()
aChecks + ["a day is chosen",nDay,8]
return aChecks
Color Mixer
A color mixer: three sliders make a color; the page shows the color, its hex code and the name of the nearest basic color.
cd samples/UsingJava/applications/ColorMixer then ring ColorMixer.ringSource code
# A color mixer: three sliders make a color; the page shows the color, its hex code and the name of the nearest basic color.
load "java.ring"
using {
"javax.swing"
"java.awt"
}
oFrame = new JFrame("Color mixer")
oFrame.setDefaultCloseOperation(2)
oFrame.setSize([380,300])
oFrame.setLocationRelativeTo(NULL)
oSwatch = new JPanel
oSwatch.setPreferredSize(Dimension_(380,90))
oControls = new JPanel((new GridLayout).@New([3,2,6,6]))
oControls.setBorder(jStatic("javax.swing.BorderFactory","createEmptyBorder",[10,10,10,10]))
aSliders = []
aLabels = []
for cName in ["Red","Green","Blue"]
oLabel = new JLabel(cName + ": 0")
oSlider = (new JSlider).@New([0,255])
oSlider.setValue(120)
oSlider.addChangeListener("onMix")
aLabels + oLabel
aSliders + oSlider
oControls.add(oLabel)
oControls.add(oSlider)
next
oHex = new JLabel(" ")
oHex.setHorizontalAlignment(0)
oHex.setFont((new Font).@New(["Monospaced",1,22]))
oFrame.add([oSwatch,"North"])
oFrame.add([oControls,"Center"])
oFrame.add([oHex,"South"])
oFrame.setVisible(true)
onMix(NULL)
jAutoClose()
jMainLoop()
func Dimension_ nW,nH
return (new Dimension).@New([nW,nH])
func onMix aArgs
nR = aSliders[1].getValue()
nG = aSliders[2].getValue()
nB = aSliders[3].getValue()
oSwatch.setBackground(jColor(nR,nG,nB))
aLabels[1].setText("Red: " + nR)
aLabels[2].setText("Green: " + nG)
aLabels[3].setText("Blue: " + nB)
oHex.setText("#" + hex2(nR) + hex2(nG) + hex2(nB) + " " + nearest(nR,nG,nB))
func hex2 nValue
return upper(right(Integer.toHexString(256 + nValue),2))
# the nearest of the basic colors, by the distance between the numbers
func nearest nR,nG,nB
aBasic = [["black",0,0,0],["white",255,255,255],["red",255,0,0],["green",0,160,0],["blue",0,0,255],["yellow",255,255,0],["cyan",0,255,255],["magenta",255,0,255],["gray",128,128,128],["orange",255,165,0]]
nBest = 0
nDistance = 999999
for nI = 1 to len(aBasic)
nD = pow(nR - aBasic[nI][2],2) + pow(nG - aBasic[nI][3],2) + pow(nB - aBasic[nI][4],2)
if nD < nDistance
nDistance = nD
nBest = nI
ok
next
return aBasic[nBest][1]
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
aSliders[1].setValue(255)
aSliders[2].setValue(0)
aSliders[3].setValue(0)
aChecks + ["red slider gives red",oHex.getText(),"#FF0000 red"]
aSliders[1].setValue(255)
aSliders[2].setValue(255)
aSliders[3].setValue(255)
aChecks + ["all sliders give white",oHex.getText(),"#FFFFFF white"]
aChecks + ["the label follows the slider",aLabels[1].getText(),"Red: 255"]
return aChecksContacts
A contacts book in a database (H2) with JavaDatabase: a console menu. ring Contacts.ring ring Contacts.ring --selftest
cd samples/UsingJava/applications/Contacts then ring Contacts.ringSource code
# A contacts book in a database (H2) with JavaDatabase: a console menu.
# ring Contacts.ring ring Contacts.ring --selftest
load "java.ring"
jMaven("com.h2database:h2:2.2.224")
aSchema = [["Contacts",[["Id","int",1],["Name","string",0],["Phone","string",0],["City","string",0]]]]
cUrl = "jdbc:h2:./contacts"
if jvSelfTestAsked()
cUrl = "jdbc:h2:mem:contacts"
ok
oDb = new JavaDatabase(cUrl,aSchema)
jAutoClose() # with --selftest: runs selfTest() and ends the program
while true
? nl + "1 add 2 list 3 find by city 4 delete 0 quit"
cChoice = trim(ask("> "))
switch cChoice
on "1"
cName = trim(ask("Name: "))
cPhone = trim(ask("Phone: "))
cCity = trim(ask("City: "))
oDb.insert("Contacts",[["Name",cName],["Phone",cPhone],["City",cCity]])
on "2"
showRows(oDb.all("Contacts"))
on "3"
showRows(oDb.where("Contacts","City = {0}",[trim(ask("City: "))]))
on "4"
oDb.remove("Contacts",number(ask("Id: ")))
on "0"
exit
on ""
exit # the end of the input
off
end
oDb.close()
# show a prompt and read a line
func ask cPrompt
see cPrompt
give cLine
return cLine
func showRows aRows
for aRow in aRows
? "" + jDbValue(aRow,"Id") + " " + jDbValue(aRow,"Name") + " " + jDbValue(aRow,"Phone") + " " + jDbValue(aRow,"City")
next
? "" + len(aRows) + " contact(s)"
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
oDb.insert("Contacts",[["Name","Ann"],["Phone","111"],["City","Cairo"]])
nBob = oDb.insert("Contacts",[["Name","Bob"],["Phone","222"],["City","Giza"]])
oDb.insert("Contacts",[["Name","Cy"],["Phone","333"],["City","Cairo"]])
aChecks + ["three contacts",oDb.count("Contacts"),3]
aChecks + ["find by city",len(oDb.where("Contacts","City = {0}",["Cairo"])),2]
oDb.update("Contacts",nBob,[["City","Cairo"]])
aChecks + ["after the update",len(oDb.where("Contacts","City = {0}",["Cairo"])),3]
oDb.remove("Contacts",nBob)
aChecks + ["after the delete",oDb.count("Contacts"),2]
return aChecks
Countdown
Countdown timer with a progress bar: a Swing timer ticks every second.
cd samples/UsingJava/applications/Countdown then ring Countdown.ringSource code
# Countdown timer with a progress bar: a Swing timer ticks every second.
load "java.ring"
using {
"javax.swing"
"java.awt"
}
nTotal = 0 # seconds when the countdown started
nLeft = 0 # seconds left
lRunning = false
oFrame = new JFrame("Countdown")
oFrame.setDefaultCloseOperation(2)
oMinutes = new JSpinner((new SpinnerNumberModel).@New([1,0,99,1]))
oSeconds = new JSpinner((new SpinnerNumberModel).@New([0,0,59,1]))
oBar = new JPanel
oBar.add(new JLabel("Minutes"))
oBar.add(oMinutes)
oBar.add(new JLabel("Seconds"))
oBar.add(oSeconds)
oDisplay = new JLabel("01:00")
oDisplay.setFont((new Font).@New(["Monospaced",1,44]))
oDisplay.setHorizontalAlignment(0)
oProgress = (new JProgressBar).@New([0,100])
oStart = new JButton("Start")
oReset = new JButton("Reset")
oStart.addActionListener("onStart")
oReset.addActionListener("onReset")
oButtons = new JPanel
oButtons.add(oStart)
oButtons.add(oReset)
oFrame.add([oBar,"North"])
oFrame.add([oDisplay,"Center"])
oSouth = new JPanel(new BorderLayout)
oSouth.setBorder(jStatic("javax.swing.BorderFactory","createEmptyBorder",[6,10,6,10]))
oSouth.add([oProgress,"North"])
oSouth.add([oButtons,"Center"])
oFrame.add([oSouth,"South"])
oFrame.setSize([360,280])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
oTimer = jTimer(1000,"onTick")
jAutoClose()
jMainLoop()
oTimer.stop()
func twoDigits n
cText = "" + floor(n)
if len(cText) < 2
cText = "0" + cText
ok
return cText
func showTime
oDisplay.setText(twoDigits(floor(nLeft / 60)) + ":" + twoDigits(nLeft % 60))
if nTotal > 0
oProgress.setValue(floor((nTotal - nLeft) * 100 / nTotal))
else
oProgress.setValue(0)
ok
func chosenSeconds
return floor(0 + oMinutes.getValue()) * 60 + floor(0 + oSeconds.getValue())
func onStart aArgs
startStop()
func startStop
if lRunning
lRunning = false
oTimer.stop()
oStart.setText("Start")
else
if nLeft = 0
nTotal = chosenSeconds()
nLeft = nTotal
ok
if nLeft > 0
lRunning = true
oTimer.start()
oStart.setText("Pause")
ok
ok
showTime()
func onReset aArgs
resetTimer()
func resetTimer
lRunning = false
oTimer.stop()
oStart.setText("Start")
nTotal = chosenSeconds()
nLeft = nTotal
showTime()
func onTick aArgs
tick()
func tick
if nLeft > 0
nLeft--
ok
showTime()
if nLeft = 0
lRunning = false
oTimer.stop()
oStart.setText("Start")
oDisplay.setText("00:00 - time is up!")
ok
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
oTimer.stop()
oMinutes.setValue(0)
oSeconds.setValue(4)
oReset.doClick()
aChecks + ["the chosen time",oDisplay.getText(),"00:04"]
oStart.doClick()
aChecks + ["the button says pause",oStart.getText(),"Pause"]
tick()
aChecks + ["one second passed",oDisplay.getText(),"00:03"]
aChecks + ["the bar",oProgress.getValue(),25]
oStart.doClick()
aChecks + ["paused",oStart.getText(),"Start"]
oStart.doClick()
tick()
tick()
tick()
aChecks + ["time is up",left(oDisplay.getText(),5),"00:00"]
aChecks + ["the bar is full",oProgress.getValue(),100]
oMinutes.setValue(2)
oSeconds.setValue(5)
oReset.doClick()
aChecks + ["reset to 2:05",oDisplay.getText(),"02:05"]
oTimer.stop()
return aChecks
Dice Roller
Dice roller: five dice drawn with their pips on a JCanvas, and statistics.
cd samples/UsingJava/applications/DiceRoller then ring DiceRoller.ringSource code
# Dice roller: five dice drawn with their pips on a JCanvas, and statistics.
load "java.ring"
using {
"javax.swing"
"java.awt"
}
C_DICE = 5
aDice = [1,1,1,1,1]
aCounts = list(6)
nRolls = 0
oCanvas = new JCanvas(420,90)
oFrame = new JFrame("Dice roller")
oFrame.setDefaultCloseOperation(2)
oRoll = new JButton("Roll")
oMany = new JButton("Roll 1000 times")
oRoll.addActionListener("onRoll")
oMany.addActionListener("onMany")
oTotal = new JLabel(" ")
oBar = new JPanel
oBar.add(oRoll)
oBar.add(oMany)
oBar.add(oTotal)
oStats = (new JTextArea).@New([8,30])
oStats.setEditable(false)
oStats.setFont((new Font).@New(["Monospaced",0,13]))
oTop = new JPanel(new BorderLayout)
oTop.add([oCanvas.component(),"North"])
oTop.add([oBar,"South"])
oFrame.add([oTop,"North"])
oFrame.add([oStats,"Center"])
oFrame.pack()
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
draw()
jAutoClose()
jMainLoop()
# the pips of a die face: positions in a 3x3 grid
func pips nFace
switch nFace
on 1 return [5]
on 2 return [1,9]
on 3 return [1,5,9]
on 4 return [1,3,7,9]
on 5 return [1,3,5,7,9]
on 6 return [1,3,4,6,7,9]
off
func drawDie nIndex, nFace
nX = 10 + (nIndex - 1) * 80
oCanvas.color("white")
oCanvas.fillRect(nX,10,70,70)
oCanvas.color("black")
oCanvas.rect(nX,10,70,70)
for nPip in pips(nFace)
nRow = floor((nPip - 1) / 3)
nCol = (nPip - 1) % 3
oCanvas.fillOval(nX + 9 + nCol * 20,19 + nRow * 20,12,12)
next
func draw
oCanvas.clear(jColor(46,125,50))
for nIndex = 1 to C_DICE
drawDie(nIndex,aDice[nIndex])
next
nSum = 0
for nFace in aDice
nSum += nFace
next
oTotal.setText("Total: " + nSum)
cText = "Rolls of a single die: " + nRolls + nl
for nFace = 1 to 6
nBar = 0
if nRolls > 0
nBar = floor(aCounts[nFace] * 30 / nRolls)
ok
cText += string(nFace) + ": " + copy("#",nBar) + " " + aCounts[nFace] + nl
next
oStats.setText(cText)
oCanvas.update()
func onRoll aArgs
rollAll()
func onMany aArgs
rollMany(1000)
func rollAll
for nIndex = 1 to C_DICE
aDice[nIndex] = random(5) + 1
aCounts[aDice[nIndex]]++
nRolls++
next
draw()
func rollMany nTimes
for nTime = 1 to nTimes
nFace = random(5) + 1
aCounts[nFace]++
nRolls++
next
draw()
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
aChecks + ["a six has six pips",len(pips(6)),6]
aChecks + ["a one has one pip",len(pips(1)),1]
oRoll.doClick()
aChecks + ["five dice were rolled",nRolls,5]
nInRange = 0
for nFace in aDice
if nFace >= 1 and nFace <= 6
nInRange++
ok
next
aChecks + ["all faces are 1 to 6",nInRange,5]
oMany.doClick()
aChecks + ["a thousand more",nRolls,1005]
nSum = 0
for nCount in aCounts
nSum += nCount
next
aChecks + ["the counts add up",nSum,1005]
aChecks + ["the total label",left(oTotal.getText(),6),"Total:"]
aChecks + ["the statistics",left(oStats.getText(),22),"Rolls of a single die:"]
return aChecks
Eight Queens
Eight queens: place 8 queens so that none attacks another. Click a square to put or remove a queen; "Solve" uses backtracking.
cd samples/UsingJava/applications/EightQueens then ring EightQueens.ringSource code
# Eight queens: place 8 queens so that none attacks another. Click a square to put or remove a queen; "Solve" uses backtracking.
load "java.ring"
using {
"javax.swing"
"java.awt"
}
C_SIZE = 8
aQueens = list(C_SIZE) # aQueens[column] = the row of the queen of that column (0 = none)
aSquares = []
oQueen = NULL # the picture of a queen (images/WQueen.png)
oFrame = new JFrame("Eight queens")
oFrame.setDefaultCloseOperation(2)
oGrid = new JPanel((new GridLayout).@New([C_SIZE,C_SIZE,0,0]))
oGrid.setBorder(jStatic("javax.swing.BorderFactory","createEmptyBorder",[8,8,8,8]))
for nCell = 1 to C_SIZE * C_SIZE
oSquare = new JButton("")
oSquare.setContentAreaFilled(false) # first: it turns opaque off, so setOpaque comes after it
oSquare.setOpaque(true)
oSquare.setFocusable(false)
oSquare.setFont((new Font).@New(["SansSerif",1,22]))
oSquare.setActionCommand("" + nCell)
oSquare.addActionListener("onSquare")
aSquares + oSquare
oGrid.add(oSquare)
next
oInfo = new JLabel("")
oSolve = new JButton("Solve")
oClear = new JButton("Clear")
oSolve.addActionListener("onSolve")
oClear.addActionListener("onClear")
oButtons = new JPanel
oButtons.add(oSolve)
oButtons.add(oClear)
oSouth = new JPanel(new BorderLayout)
oSouth.add([oInfo,"Center"])
oSouth.add([oButtons,"East"])
oFrame.add([oGrid,"Center"])
oFrame.add([oSouth,"South"])
oFrame.setSize([420,500])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
loadQueen()
showBoard()
jAutoClose()
jMainLoop()
func squareOf nRow, nColumn
return (nRow - 1) * C_SIZE + nColumn
# do two queens (row, column) attack each other
func attacks nRow1, nColumn1, nRow2, nColumn2
if nRow1 = nRow2 or nColumn1 = nColumn2
return true
ok
return fabs(nRow1 - nRow2) = fabs(nColumn1 - nColumn2)
# the columns whose queen is attacked by another queen
func conflicts
aBad = list(C_SIZE)
for nA = 1 to C_SIZE
for nB = nA + 1 to C_SIZE
if aQueens[nA] > 0 and aQueens[nB] > 0 and attacks(aQueens[nA],nA,aQueens[nB],nB)
aBad[nA] = 1
aBad[nB] = 1
ok
next
next
return aBad
# the picture is in the folder images next to the program, scaled to fit a square
func loadQueen
cFolder = ""
if len(sysargv) > 1
cFolder = jFolderOf(sysargv[2])
ok
oPicture = new ImageIcon(cFolder + "images/WQueen.png")
oQueen = new ImageIcon(oPicture.getImage().getScaledInstance(40,40,4))
func showBoard
aBad = conflicts()
nPlaced = 0
for nRow = 1 to C_SIZE
for nColumn = 1 to C_SIZE
oSquare = aSquares[squareOf(nRow,nColumn)]
if (nRow + nColumn) % 2 = 0
oSquare.setBackground(jColor(245,222,179))
else
oSquare.setBackground(jColor(160,82,45))
ok
if aQueens[nColumn] = nRow
oSquare.setIcon(oQueen)
nPlaced++
if aBad[nColumn] # a queen that is attacked: its square is red
oSquare.setBackground(jColor(225,70,70))
ok
else
oSquare.setIcon(NULL)
ok
next
next
nBad = 0
for nValue in aBad
nBad += nValue
next
if nPlaced = C_SIZE and nBad = 0
oInfo.setText(" Solved!")
else
oInfo.setText(" Queens: " + nPlaced + "/8 conflicts: " + nBad)
ok
func toggle nRow, nColumn
if aQueens[nColumn] = nRow
aQueens[nColumn] = 0
else
aQueens[nColumn] = nRow
ok
showBoard()
func onSquare aArgs
nCell = 0 + aArgs[1].getActionCommand()
toggle(floor((nCell - 1) / C_SIZE) + 1,(nCell - 1) % C_SIZE + 1)
func onClear aArgs
clearBoard()
func clearBoard
aQueens = list(C_SIZE)
showBoard()
func onSolve aArgs
aQueens = firstSolution()
showBoard()
# the number of ways to complete the board from column nColumn (backtracking)
func countSolutions nColumn, aPlaced
if nColumn > C_SIZE
return 1
ok
nTotal = 0
for nRow = 1 to C_SIZE
lSafe = true
for nBefore = 1 to nColumn - 1
if attacks(aPlaced[nBefore],nBefore,nRow,nColumn)
lSafe = false
exit
ok
next
if lSafe
aPlaced[nColumn] = nRow
nTotal += countSolutions(nColumn + 1,aPlaced)
aPlaced[nColumn] = 0
ok
next
return nTotal
# a solution found by backtracking
func firstSolution
aResult = list(C_SIZE)
findOne(1,aResult)
return aResult
func findOne nColumn, aPlaced
if nColumn > C_SIZE
return true
ok
for nRow = 1 to C_SIZE
lSafe = true
for nBefore = 1 to nColumn - 1
if attacks(aPlaced[nBefore],nBefore,nRow,nColumn)
lSafe = false
exit
ok
next
if lSafe
aPlaced[nColumn] = nRow
if findOne(nColumn + 1,aPlaced)
return true
ok
aPlaced[nColumn] = 0
ok
next
return false
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
aQueens = list(C_SIZE)
aSquares[squareOf(1,1)].doClick()
aSquares[squareOf(2,2)].doClick()
aChecks + ["two queens on a diagonal attack",conflicts()[1] + conflicts()[2],2]
aChecks + ["the square shows a queen",jIsNull(aSquares[squareOf(1,1)].getIcon()),false]
aChecks + ["an empty square has no picture",jIsNull(aSquares[squareOf(3,1)].getIcon()),true]
aChecks + ["and the conflict is in red",aSquares[squareOf(1,1)].getBackground().getRed(),225]
aSquares[squareOf(2,2)].doClick()
aChecks + ["clicking again removes it",aQueens[2],0]
aChecks + ["no conflict now",left(trim(oInfo.getText()),9),"Queens: 1"]
oSolve.doClick()
aChecks + ["solved",trim(oInfo.getText()),"Solved!"]
aChecks + ["the first solution starts at row 1",aQueens[1],1]
aChecks + ["there are 92 solutions",countSolutions(1,list(C_SIZE)),92]
oClear.doClick()
aChecks + ["clear",aQueens[1],0]
return aChecks
Epoch Time
Epoch (Unix) time converter: both directions, UTC and local time. The dates come from java.time.
cd samples/UsingJava/applications/EpochTime then ring EpochTime.ringSource code
# Epoch (Unix) time converter: both directions, UTC and local time. The dates come from java.time.
load "java.ring"
using {
"javax.swing"
"java.awt"
}
C_FORMAT = "yyyy-MM-dd HH:mm:ss"
oFrame = new JFrame("Epoch time converter")
oFrame.setDefaultCloseOperation(2)
oEpoch = new JTextField("")
oUtc = new JTextField("")
oLocal = new JTextField("")
oLocal.setEditable(false)
oToDate = new JButton("Convert")
oToEpoch = new JButton("To epoch")
oNow = new JButton("Now")
oToDate.addActionListener("onToDate")
oToEpoch.addActionListener("onToEpoch")
oNow.addActionListener("onNow")
oForm = new JPanel((new GridLayout).@New([4,3,8,8]))
oForm.setBorder(jStatic("javax.swing.BorderFactory","createEmptyBorder",[12,12,4,12]))
oForm.add(new JLabel("Epoch (seconds)"))
oForm.add(oEpoch)
oForm.add(oToDate)
oForm.add(new JLabel("UTC date"))
oForm.add(oUtc)
oForm.add(oToEpoch)
oForm.add(new JLabel("Local time"))
oForm.add(oLocal)
oForm.add(new JLabel(""))
oForm.add(new JLabel(""))
oForm.add(oNow)
oForm.add(new JLabel(""))
oMessage = new JLabel(" ")
oMessage.setForeground(jColor(178,34,34))
oFrame.add([oForm,"Center"])
oFrame.add([oMessage,"South"])
oFrame.setSize([560,230])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
jAutoClose()
jMainLoop()
func formatter
return jStatic("java.time.format.DateTimeFormatter","ofPattern",[C_FORMAT])
# the epoch (seconds) of a UTC date text; raises an error for invalid text
func epochOf cDateText
oDate = jStatic("java.time.LocalDateTime","parse",[cDateText,formatter()])
return oDate.toEpochSecond(jGetStatic("java.time.ZoneOffset","UTC"))
# [UTC text, local text] of an epoch
func datesOf nEpoch
oInstant = jStatic("java.time.Instant","ofEpochSecond",[nEpoch])
oUtcDate = jStatic("java.time.LocalDateTime","ofInstant",[oInstant,jGetStatic("java.time.ZoneOffset","UTC")])
oLocalDate = jStatic("java.time.LocalDateTime","ofInstant",[oInstant,jStatic("java.time.ZoneId","systemDefault",[])])
return [oUtcDate.format(formatter()),oLocalDate.format(formatter())]
func onToDate aArgs
epochToDate()
func onToEpoch aArgs
dateToEpoch()
func onNow aArgs
showNow()
func epochToDate
oMessage.setText(" ")
cEpoch = trim(oEpoch.getText())
if cEpoch = "" or not isdigit(substr(cEpoch,"-","")[1])
oMessage.setText("Invalid epoch value")
return
ok
try
aDates = datesOf(floor(number(cEpoch)))
oUtc.setText(aDates[1])
oLocal.setText(aDates[2])
catch
oMessage.setText("Invalid epoch value")
done
func dateToEpoch
oMessage.setText(" ")
try
nEpoch = epochOf(trim(oUtc.getText()))
oEpoch.setText("" + floor(nEpoch))
epochToDate()
catch
oMessage.setText("Invalid date (use yyyy-MM-dd HH:mm:ss)")
done
func showNow
oEpoch.setText("" + floor(jStatic("java.time.Instant","now",[]).getEpochSecond()))
epochToDate()
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
oEpoch.setText("0")
oToDate.doClick()
aChecks + ["the epoch 0",oUtc.getText(),"1970-01-01 00:00:00"]
aChecks + ["its local text has the format",len(oLocal.getText()),19]
oEpoch.setText("1700000000")
oToDate.doClick()
aChecks + ["1.7 billion",oUtc.getText(),"2023-11-14 22:13:20"]
oEpoch.setText("")
oUtc.setText("2000-01-01 00:00:00")
oToEpoch.doClick()
aChecks + ["the year 2000",oEpoch.getText(),"946684800"]
oUtc.setText("yesterday")
oToEpoch.doClick()
aChecks + ["a bad date",left(oMessage.getText(),12),"Invalid date"]
oEpoch.setText("abc")
oToDate.doClick()
aChecks + ["a bad epoch",oMessage.getText(),"Invalid epoch value"]
oNow.doClick()
aChecks + ["now is after 2023",number(oEpoch.getText()) > 1700000000,true]
return aChecksExpense Tracker
An expense tracker: JavaDatabase keeps the rows, a JTable lists them and a JCanvas draws the total of each category.
cd samples/UsingJava/applications/ExpenseTracker then ring ExpenseTracker.ringSource code
# An expense tracker: JavaDatabase keeps the rows, a JTable lists them and a JCanvas draws the total of each category.
load "java.ring"
using {
"javax.swing.table"
}
jMaven("com.h2database:h2:2.2.224")
oDb = new JavaDatabase("jdbc:h2:mem:expenses",[
["Expenses",[
["Id","int",1],
["Spent","string",0],
["Category","string",0,[["index",1]]],
["Amount","double",0],
["Note","string",0]
]]
])
aCategories = ["Food","Transport","Books","Fun"]
aSeed = [
["2024-05-01","Food",12.5,"Lunch"],
["2024-05-02","Transport",3,"Bus"],
["2024-05-03","Books",45,"Ring book"],
["2024-05-04","Food",8.75,"Coffee and cake"],
["2024-05-05","Fun",20,"Cinema"]
]
for aItem in aSeed
oDb.insert("Expenses",[["Spent",aItem[1]],["Category",aItem[2]],["Amount",aItem[3]],["Note",aItem[4]]])
next
oWin = jWindow("Expenses",640,520)
oDay = jField("2024-05-06",10,"")
oCategory = jCombo(aCategories,"")
oAmount = jField("",8,"onAdd")
oNote = jField("",14,"onAdd")
oAdd = jButton("Add","onAdd")
oDelete = jButton("Delete selected","onDelete")
oModel = (new DefaultTableModel).@New([jArray("java.lang.String",["Id","Date","Category","Amount","Note"]),0])
oTable = new JTable(oModel)
oCanvas = new JCanvas(600,170)
oTotal = jLabel(" ")
oWin.add([jBorder(
jScroll(oTable),
jPad(jRow([oDay,oCategory,oAmount,oNote,oAdd,oDelete],6),6),
jColumn([oCanvas.component(),oTotal],4),
NULL,
NULL
),"Center"])
refresh()
jShow(oWin)
jAutoClose()
jMainLoop()
oDb.close()
func refresh
oModel.setRowCount(0)
for aRow in oDb.query("Expenses",[["orderby",[["Id","asc"]]]])
oModel.addRow(jArray("java.lang.Object",[jDbValue(aRow,"id"),jDbValue(aRow,"spent"),jDbValue(aRow,"category"),jDbValue(aRow,"amount"),jDbValue(aRow,"note")]))
next
nTotalAmount = oDb.sum("Expenses","Amount",[])
oTotal.setText(" " + oDb.count("Expenses") + " expenses, total " + nTotalAmount)
drawChart()
func drawChart
oCanvas.clear("white")
aTotals = []
nMax = 1
for cName in aCategories
nSum = oDb.sum("Expenses","Amount",["Category","=",cName])
if not isnumber(nSum)
nSum = 0
ok
aTotals + nSum
if nSum > nMax
nMax = nSum
ok
next
aColours = ["orange","blue","green","magenta"]
for nAt = 1 to len(aCategories)
nHeight = floor(aTotals[nAt] / nMax * 110)
nX = 40 + (nAt - 1) * 140
oCanvas.color(aColours[nAt])
oCanvas.fillRect(nX,130 - nHeight,90,nHeight)
oCanvas.color("black")
oCanvas.text(aCategories[nAt] + " " + aTotals[nAt],nX,150)
next
oCanvas.update()
func onAdd aArgs
cAmount = trim(oAmount.getText())
if cAmount = "" or not isDecimal(cAmount)
oTotal.setText(" The amount must be a number")
return
ok
oDb.insert("Expenses",[["Spent",oDay.getText()],["Category",oCategory.getSelectedItem()],["Amount",0 + cAmount],["Note",oNote.getText()]])
oAmount.setText("")
oNote.setText("")
refresh()
# digits with at most one point: "12", "3.50" (text such as "abc" would become 0 and be stored as an expense of 0)
func isDecimal cText
nPoints = 0
nDigits = 0
for nPos = 1 to len(cText)
if cText[nPos] = "."
nPoints++
but isdigit(cText[nPos])
nDigits++
else
return false
ok
next
return nPoints <= 1 and nDigits > 0
func onDelete aArgs
nRow = oTable.getSelectedRow()
if nRow >= 0
oDb.remove("Expenses",oModel.getValueAt(nRow,0))
refresh()
ok
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
aChecks + ["the expenses at the start",oModel.getRowCount(),5]
oAmount.setText("12.5")
oAdd.doClick()
aChecks + ["Add",oModel.getRowCount(),6]
aChecks + ["the total",oDb.sum("Expenses","Amount",[]),101.75]
oTable.setRowSelectionInterval(0,0)
oDelete.doClick()
aChecks + ["Delete",oModel.getRowCount(),5]
oAmount.setText("abc")
nRowsBefore = oDb.count("Expenses")
oAdd.doClick()
aChecks + ["text is not an amount",oDb.count("Expenses"),nRowsBefore]
aChecks + ["decimal numbers",isDecimal("3.50") and not isDecimal("1.2.3") and not isDecimal(".") and not isDecimal("12a"),true]
return aChecks
Fifteen Puzzle
Fifteen puzzle: slide the tiles into order. A tile next to the empty cell moves when you click it.
cd samples/UsingJava/applications/FifteenPuzzle then ring FifteenPuzzle.ringSource code
# Fifteen puzzle: slide the tiles into order. A tile next to the empty cell moves when you click it.
load "java.ring"
using {
"javax.swing"
"java.awt"
}
C_SIZE = 4
aTiles = [] # aTiles[cell] = tile number (0 = the empty cell)
aCells = [] # the buttons
nMoves = 0
oFrame = new JFrame("Fifteen puzzle")
oFrame.setDefaultCloseOperation(2)
oGrid = new JPanel((new GridLayout).@New([C_SIZE,C_SIZE,4,4]))
oGrid.setBorder(jStatic("javax.swing.BorderFactory","createEmptyBorder",[8,8,8,8]))
for nCell = 1 to C_SIZE * C_SIZE
oCell = new JButton("")
oCell.setFont((new Font).@New(["SansSerif",1,24]))
oCell.setActionCommand("" + nCell)
oCell.addActionListener("onCell")
aCells + oCell
oGrid.add(oCell)
aTiles + (nCell % (C_SIZE * C_SIZE))
next
oMoves = new JLabel("Moves: 0")
oShuffle = new JButton("Shuffle")
oShuffle.addActionListener("onShuffle")
oSouth = new JPanel(new BorderLayout)
oSouth.add([oMoves,"Center"])
oSouth.add([oShuffle,"East"])
oFrame.add([oGrid,"Center"])
oFrame.add([oSouth,"South"])
oFrame.setSize([340,420])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
shuffleBoard()
jAutoClose()
jMainLoop()
func showBoard
for nCell = 1 to len(aTiles)
if aTiles[nCell] = 0
aCells[nCell].setText("")
aCells[nCell].setBackground(jColor(220,220,220))
else
aCells[nCell].setText("" + aTiles[nCell])
aCells[nCell].setBackground(jColor(255,255,255))
ok
next
if isSolved()
oMoves.setText("Solved in " + nMoves + " moves!")
else
oMoves.setText("Moves: " + nMoves)
ok
func emptyCell
return find(aTiles,0)
# cells that touch the cell
func neighbors nCell
aList = []
nRow = floor((nCell - 1) / C_SIZE)
nCol = (nCell - 1) % C_SIZE
if nRow > 0 aList + (nCell - C_SIZE) ok
if nRow < C_SIZE - 1 aList + (nCell + C_SIZE) ok
if nCol > 0 aList + (nCell - 1) ok
if nCol < C_SIZE - 1 aList + (nCell + 1) ok
return aList
func slideTile nCell
nEmpty = emptyCell()
if find(neighbors(nEmpty),nCell) > 0
aTiles[nEmpty] = aTiles[nCell]
aTiles[nCell] = 0
return true
ok
return false
func clickCell nCell
if slideTile(nCell)
nMoves++
showBoard()
ok
func onCell aArgs
clickCell(0 + aArgs[1].getActionCommand())
func isSolved
for nCell = 1 to len(aTiles) - 1
if aTiles[nCell] != nCell
return false
ok
next
return true
func onShuffle aArgs
shuffleBoard()
# shuffle with legal moves only, so the puzzle is always solvable
func shuffleBoard
for nCell = 1 to len(aTiles)
aTiles[nCell] = nCell % len(aTiles)
next
for nStep = 1 to 200
aNear = neighbors(emptyCell())
slideTile(aNear[random(len(aNear) - 1) + 1])
next
nMoves = 0
showBoard()
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
aChecks + ["a shuffled board has one empty cell",find(aTiles,0) > 0,true]
for nCell = 1 to len(aTiles)
aTiles[nCell] = nCell % len(aTiles)
next
nMoves = 0
aChecks + ["the ordered board is solved",isSolved(),true]
aCells[15].doClick()
aChecks + ["a tile moves into the empty cell",aTiles[16],15]
aChecks + ["and counts as a move",nMoves,1]
aCells[1].doClick()
aChecks + ["a far tile does not move",nMoves,1]
aChecks + ["the board is no longer solved",isSolved(),false]
aCells[16].doClick()
aChecks + ["moving back solves it",oMoves.getText(),"Solved in 2 moves!"]
return aChecks
File Explorer
File explorer: a tree of folders on the left, the files of the selected folder in a table on the right.
cd samples/UsingJava/applications/FileExplorer then ring FileExplorer.ringSource code
# File explorer: a tree of folders on the left, the files of the selected folder in a table on the right.
load "java.ring"
using {
"javax.swing"
"javax.swing.tree"
"javax.swing.event"
"javax.swing.table"
"java.awt"
"java.io"
"java.util"
}
cStart = (new File).@New([currentdir() + "/../.."]).getCanonicalPath()
oPaths = new HashMap # the path of each node of the tree (the node shows only the name)
oRoot = new DefaultMutableTreeNode((new File).@New([cStart]).getName())
oPaths.@put(oRoot,cStart)
add_folders(oRoot,cStart)
oTree = new JTree(oRoot)
oModel = (new DefaultTableModel).@New([jArray("java.lang.String",["Name","Size","Kind"]),0])
oTable = new JTable(oModel)
oStatus = new JLabel(" ")
oSplit = (new JSplitPane).@New([1,new JScrollPane(oTree),new JScrollPane(oTable)])
oSplit.setDividerLocation(220)
oFrame = new JFrame("File explorer")
oFrame.setDefaultCloseOperation(2)
oFrame.add([oSplit,"Center"])
oFrame.add([oStatus,"South"])
oFrame.setSize([720,420])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
oTree.addTreeSelectionListener("onSelect")
oTree.addTreeWillExpandListener("onExpand")
oTree.expandRow(0)
oTree.setSelectionRow(0)
jAutoClose()
jMainLoop()
func add_folders oNode,cPath
oDir = new File(cPath)
aFiles = jToList(oDir.listFiles())
if isnull(aFiles) or len(aFiles) = 0
return
ok
for oFile in aFiles
if oFile.isDirectory() and not oFile.isHidden()
oChild = new DefaultMutableTreeNode(oFile.getName())
oPaths.@put(oChild,oFile.getAbsolutePath())
oChild.add(new DefaultMutableTreeNode("...")) # placeholder so that the node can expand
oNode.add(oChild)
ok
next
func onExpand aArgs
if cJavaMethod != "treeWillExpand"
return
ok
oNode = aArgs[1].getPath().getLastPathComponent()
if oNode.getChildCount() = 1 and oNode.getFirstChild().toString() = "..."
oNode.removeAllChildren()
add_folders(oNode,oPaths.@get(oNode))
oTree.getModel().nodeStructureChanged(oNode)
ok
func onSelect aArgs
oNode = oTree.getLastSelectedPathComponent()
if isnull(oNode)
return
ok
oDir = (new File).@New([oPaths.@get(oNode)])
oModel.setRowCount(0)
aFiles = jToList(oDir.listFiles())
nCount = 0
if not isnull(aFiles)
for oFile in aFiles
if oFile.isDirectory()
cKind = "Folder"
cSize = ""
else
cKind = "File"
cSize = "" + oFile.length() + " bytes"
ok
oModel.addRow(jArray("java.lang.Object",[oFile.getName(),cSize,cKind]))
nCount++
next
ok
oStatus.setText(" " + oDir.getAbsolutePath() + " - " + nCount + " items")
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
aChecks + ["the start folder is listed",oModel.getRowCount() > 0,1]
aChecks + ["the status names the items",substr(oStatus.getText()," items") > 0,1]
aChecks + ["the root of the tree",oTree.getRowCount() > 0,1]
return aChecks
Game2048
2048: the arrow keys slide the tiles, equal tiles that meet are joined. The board is drawn on a JCanvas.
cd samples/UsingJava/applications/Game2048 then ring Game2048.ringSource code
# 2048: the arrow keys slide the tiles, equal tiles that meet are joined. The board is drawn on a JCanvas.
load "java.ring"
using {
"javax.swing"
"java.awt.event"
}
C_SIZE = 4
C_TILE = 80
aBoard = list(C_SIZE * C_SIZE) # 0 = empty
nScore = 0
lGameOver = false
oCanvas = new JCanvas(C_SIZE * C_TILE + 10,C_SIZE * C_TILE + 10)
oStatus = new JLabel("Score: 0 (arrow keys move, R restarts)")
oFrame = new JFrame("2048")
oFrame.setDefaultCloseOperation(2)
oFrame.add([oCanvas.component(),"Center"])
oFrame.add([oStatus,"South"])
oFrame.pack()
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
oCanvas.component().setFocusable(true)
oCanvas.component().addKeyListener("onKey")
oCanvas.component().requestFocus()
newGame()
jAutoClose()
jMainLoop()
func tileColor nValue
switch nValue
on 0 return jColor(205,193,180)
on 2 return jColor(238,228,218)
on 4 return jColor(237,224,200)
on 8 return jColor(242,177,121)
on 16 return jColor(245,149,99)
on 32 return jColor(246,124,95)
on 64 return jColor(246,94,59)
on 128 return jColor(237,207,114)
on 256 return jColor(237,204,97)
on 512 return jColor(237,200,80)
other return jColor(237,194,46)
off
func showBoard
oCanvas.clear(jColor(187,173,160))
oCanvas.font("SansSerif",24,true)
for nCell = 1 to len(aBoard)
nX = ((nCell - 1) % C_SIZE) * C_TILE + 10
nY = floor((nCell - 1) / C_SIZE) * C_TILE + 10
oCanvas.color(tileColor(aBoard[nCell]))
oCanvas.fillRoundRect(nX,nY,C_TILE - 10,C_TILE - 10,10)
if aBoard[nCell] > 0
cText = "" + aBoard[nCell]
if aBoard[nCell] <= 4
oCanvas.color(jColor(119,110,101))
else
oCanvas.color(jColor(255,255,255))
ok
oCanvas.text(cText,nX + floor((C_TILE - 10 - oCanvas.textWidth(cText)) / 2),nY + floor((C_TILE - 10) / 2) + 9)
ok
next
oCanvas.update()
oStatus.setText("Score: " + nScore + " (arrow keys move, R restarts)")
# slide one line to the left: [new line, points gained]
func slideLine aLine
aKept = []
for nValue in aLine
if nValue != 0
aKept + nValue
ok
next
aOut = []
nGained = 0
nIndex = 1
while nIndex <= len(aKept)
if nIndex < len(aKept) and aKept[nIndex] = aKept[nIndex + 1]
aOut + (aKept[nIndex] * 2)
nGained += aKept[nIndex] * 2
nIndex += 2
else
aOut + aKept[nIndex]
nIndex++
ok
end
while len(aOut) < len(aLine)
aOut + 0
end
return [aOut,nGained]
# move the whole board: "Left" "Right" "Up" "Down"; true when something moved
func moveBoard cDirection
lMoved = false
for nLine = 1 to C_SIZE
aLine = []
for nStep = 1 to C_SIZE
aLine + aBoard[cellIndex(nLine,nStep,cDirection)]
next
aResult = slideLine(aLine)
for nStep = 1 to C_SIZE
nIndex = cellIndex(nLine,nStep,cDirection)
if aBoard[nIndex] != aResult[1][nStep]
lMoved = true
aBoard[nIndex] = aResult[1][nStep]
ok
next
nScore += aResult[2]
next
return lMoved
# the cell that is the nStep-th of line nLine when sliding in cDirection (nStep 1 = the cell the tiles slide to)
func cellIndex nLine, nStep, cDirection
switch cDirection
on "Left"
return (nLine - 1) * C_SIZE + nStep
on "Right"
return (nLine - 1) * C_SIZE + (C_SIZE + 1 - nStep)
on "Up"
return (nStep - 1) * C_SIZE + nLine
on "Down"
return (C_SIZE - nStep) * C_SIZE + nLine
off
func addRandomTile
aFree = []
for nCell = 1 to len(aBoard)
if aBoard[nCell] = 0
aFree + nCell
ok
next
if len(aFree) > 0
if random(9) = 0
aBoard[aFree[random(len(aFree) - 1) + 1]] = 4
else
aBoard[aFree[random(len(aFree) - 1) + 1]] = 2
ok
ok
func canMove
for cDirection in ["Left","Right","Up","Down"]
aSaved = aBoard
nSavedScore = nScore
lPossible = moveBoard(cDirection)
aBoard = aSaved
nScore = nSavedScore
if lPossible
return true
ok
next
return false
func move cDirection
if lGameOver
return
ok
if moveBoard(cDirection)
addRandomTile()
if not canMove()
lGameOver = true
oStatus.setText("Game over - score " + nScore + " (R restarts)")
ok
ok
showBoard()
if lGameOver
oStatus.setText("Game over - score " + nScore + " (R restarts)")
ok
func onKey aArgs
if cJavaMethod != "keyPressed"
return
ok
nCode = aArgs[1].getKeyCode()
if nCode = 37
move("Left")
but nCode = 39
move("Right")
but nCode = 38
move("Up")
but nCode = 40
move("Down")
but nCode = 82
newGame()
ok
func newGame
aBoard = list(C_SIZE * C_SIZE)
nScore = 0
lGameOver = false
addRandomTile()
addRandomTile()
showBoard()
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
aSlid = slideLine([2,2,4,0])
aChecks + ["slide and join",list2str(aSlid[1]),"4" + nl + "4" + nl + "0" + nl + "0"]
aChecks + ["points of a join",aSlid[2],4]
aSlid = slideLine([2,2,2,2])
aChecks + ["no double join",aSlid[1][1] + aSlid[1][2] + aSlid[1][3],8]
aChecks + ["points of two joins",aSlid[2],8]
aBoard = [2,0,0,2, 0,0,0,0, 0,0,0,0, 4,4,0,0]
nScore = 0
aChecks + ["move left",moveBoard("Left"),true]
aChecks + ["row 1",aBoard[1] * 10 + aBoard[2],40]
aChecks + ["row 4",aBoard[13] * 10 + aBoard[14],80]
aChecks + ["score",nScore,12]
aBoard = [2,4,2,4, 4,2,4,2, 2,4,2,4, 4,2,4,2]
aChecks + ["a full board cannot move",canMove(),false]
newGame()
nTiles = 0
for nValue in aBoard
if nValue > 0
nTiles++
ok
next
aChecks + ["new game has two tiles",nTiles,2]
return aChecks
Game Of Life
Conway's Game of Life: a grid of cells, a timer makes the next generation; click a cell to flip it.
cd samples/UsingJava/applications/GameOfLife then ring GameOfLife.ringSource code
# Conway's Game of Life: a grid of cells, a timer makes the next generation; click a cell to flip it.
load "java.ring"
using {
"javax.swing"
"java.awt"
"java.awt.image"
"java.awt.event"
}
nCols = 40
nRows = 28
nCell = 12
aGrid = []
for nY = 1 to nRows
aRow = list(nCols)
for nX = 1 to nCols
aRow[nX] = 0
next
aGrid + aRow
next
nGeneration = 0
lRunning = true
# a glider gun is long: a few gliders and an R-pentomino are enough to watch
for aCell in [[2,1],[3,2],[1,3],[2,3],[3,3]]
aGrid[aCell[2] + 2][aCell[1] + 2] = 1
next
for aCell in [[2,1],[3,1],[1,2],[2,2],[2,3]]
aGrid[aCell[2] + 12][aCell[1] + 20] = 1
next
oImage = (new BufferedImage).@New([nCols * nCell,nRows * nCell,1])
oLabel = new JLabel(new ImageIcon(oImage))
oInfo = new JLabel("Generation 0")
oPause = new JButton("Pause")
oClear = new JButton("Clear")
oSouth = new JPanel
oSouth.add(oPause)
oSouth.add(oClear)
oSouth.add(oInfo)
oFrame = new JFrame("Game of Life")
oFrame.setDefaultCloseOperation(2)
oFrame.add([oLabel,"Center"])
oFrame.add([oSouth,"South"])
oFrame.pack()
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
oPause.addActionListener("onPause")
oClear.addActionListener("onClear")
oLabel.addMouseListener("onMouse")
oTimer = jTimer(150,"onTick")
oTimer.start()
draw()
jAutoClose()
jMainLoop()
oTimer.stop()
func onPause aArgs
lRunning = not lRunning
if lRunning
oPause.setText("Pause")
else
oPause.setText("Run")
ok
func onClear aArgs
for nY = 1 to nRows
for nX = 1 to nCols
aGrid[nY][nX] = 0
next
next
nGeneration = 0
draw()
func onMouse aArgs
if cJavaMethod != "mousePressed"
return
ok
nX = floor(aArgs[1].getX() / nCell) + 1
nY = floor(aArgs[1].getY() / nCell) + 1
if nX >= 1 and nX <= nCols and nY >= 1 and nY <= nRows
aGrid[nY][nX] = 1 - aGrid[nY][nX]
draw()
ok
func onTick aArgs
if not lRunning
return
ok
aNext = []
for nY = 1 to nRows
aRow = list(nCols)
for nX = 1 to nCols
nAlive = neighbours(nX,nY)
if aGrid[nY][nX] = 1
if nAlive = 2 or nAlive = 3
aRow[nX] = 1
else
aRow[nX] = 0
ok
else
if nAlive = 3
aRow[nX] = 1
else
aRow[nX] = 0
ok
ok
next
aNext + aRow
next
aGrid = aNext
nGeneration++
draw()
# the grid is a torus: the left edge touches the right edge
func neighbours nX,nY
nCount = 0
for nDY = -1 to 1
for nDX = -1 to 1
if nDX != 0 or nDY != 0
nCount += aGrid[1 + (nY - 1 + nDY + nRows) % nRows][1 + (nX - 1 + nDX + nCols) % nCols]
ok
next
next
return nCount
func draw
g = oImage.createGraphics()
g.setColor(jColor(250,250,245))
g.fillRect(0,0,nCols * nCell,nRows * nCell)
g.setColor(jColor(30,90,160))
for nY = 1 to nRows
for nX = 1 to nCols
if aGrid[nY][nX] = 1
g.fillRect((nX - 1) * nCell + 1,(nY - 1) * nCell + 1,nCell - 1,nCell - 1)
ok
next
next
g.dispose()
oLabel.repaint()
oInfo.setText("Generation " + nGeneration)
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
nAlive = 0
for aRow in aGrid
nAlive += sum_row(aRow)
next
aChecks + ["the cells at the start",nAlive,10]
onTick(NULL)
aChecks + ["a generation",nGeneration,1]
onPause(NULL)
aChecks + ["Pause",oPause.getText(),"Run"]
onTick(NULL)
aChecks + ["a paused game does not move",nGeneration,1]
onClear(NULL)
nAlive = 0
for aRow in aGrid
nAlive += sum_row(aRow)
next
aChecks + ["Clear",nAlive,0]
return aChecks
func sum_row aRow
nSum = 0
for nCell2 in aRow
nSum += nCell2
next
return nSum
Hangman
Hangman: guess the word letter by letter; the gallows is drawn on a JCanvas.
cd samples/UsingJava/applications/Hangman then ring Hangman.ringSource code
# Hangman: guess the word letter by letter; the gallows is drawn on a JCanvas.
load "java.ring"
using {
"javax.swing"
"java.awt"
}
aWords = ["RING","PROGRAMMING","LANGUAGE","WINDOWS","SWING","EXTENSION","CALCULATOR","KEYBOARD","DEVELOPER","FUNCTION"]
cWord = ""
cGuessed = ""
nWrong = 0
C_MAXWRONG = 6
aLetterButtons = []
oCanvas = new JCanvas(200,200)
oWord = new JLabel("")
oWord.setFont((new Font).@New(["Monospaced",1,22]))
oInfo = new JLabel("")
oRight = new JPanel((new GridLayout).@New([3,1,4,4]))
oRight.add(oWord)
oRight.add(oInfo)
oNew = new JButton("New word")
oNew.addActionListener("onNew")
oRight.add(oNew)
oTop = new JPanel(new BorderLayout)
oTop.add([oCanvas.component(),"West"])
oTop.add([oRight,"Center"])
oKeys = new JPanel((new GridLayout).@New([3,9,3,3]))
for nLetter = 0 to 25
cLetter = char(65 + nLetter)
oButton = new JButton(cLetter)
oButton.setMargin((new Insets).@New([2,2,2,2]))
oButton.setActionCommand(cLetter)
oButton.addActionListener("onLetter")
aLetterButtons + oButton
oKeys.add(oButton)
next
oFrame = new JFrame("Hangman")
oFrame.setDefaultCloseOperation(2)
oFrame.add([oTop,"Center"])
oFrame.add([oKeys,"South"])
oFrame.setSize([480,380])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
newGame()
jAutoClose()
jMainLoop()
func onNew aArgs
newGame()
func newGame
cWord = aWords[random(len(aWords) - 1) + 1]
cGuessed = ""
nWrong = 0
for oButton in aLetterButtons
oButton.setEnabled(true)
next
showState()
# the word with the unknown letters as underscores
func maskedWord
cMask = ""
for x = 1 to len(cWord)
if substr(cGuessed,cWord[x])
cMask += cWord[x] + " "
else
cMask += "_ "
ok
next
return trim(cMask)
func isWon
return substr(maskedWord(),"_") = 0
func onLetter aArgs
letter(aArgs[1].getActionCommand())
func letter cLetter
if substr(cGuessed,cLetter) or nWrong >= C_MAXWRONG or isWon()
return
ok
cGuessed += cLetter
aLetterButtons[ascii(cLetter) - 64].setEnabled(false)
if not substr(cWord,cLetter)
nWrong++
ok
showState()
func drawGallows
oCanvas.clear("white")
oCanvas.color("black")
oCanvas.lineWidth(4)
oCanvas.line(20,190,180,190)
oCanvas.line(60,190,60,20)
oCanvas.line(60,20,130,20)
oCanvas.lineWidth(3)
oCanvas.line(130,20,130,40)
if nWrong >= 1 oCanvas.oval(118,40,24,24) ok
if nWrong >= 2 oCanvas.line(130,64,130,115) ok
if nWrong >= 3 oCanvas.line(130,75,110,100) ok
if nWrong >= 4 oCanvas.line(130,75,150,100) ok
if nWrong >= 5 oCanvas.line(130,115,112,145) ok
if nWrong >= 6 oCanvas.line(130,115,148,145) ok
oCanvas.update()
func showState
oWord.setText(maskedWord())
if isWon()
oInfo.setText("You won!")
but nWrong >= C_MAXWRONG
oInfo.setText("You lost. The word was " + cWord)
oWord.setText(cWord)
else
oInfo.setText("Wrong guesses: " + nWrong + " of " + C_MAXWRONG)
ok
drawGallows()
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
cWord = "RING"
cGuessed = ""
nWrong = 0
showState()
aChecks + ["the word is hidden",oWord.getText(),"_ _ _ _"]
letter("R")
aChecks + ["a right letter shows",oWord.getText(),"R _ _ _"]
aChecks + ["and does not count as wrong",nWrong,0]
letter("Z")
aChecks + ["a wrong letter counts",nWrong,1]
aChecks + ["its key is disabled",aLetterButtons[26].isEnabled(),false]
letter("Z")
aChecks + ["the same letter is ignored",nWrong,1]
letter("I")
letter("N")
letter("G")
aChecks + ["the game is won",oInfo.getText(),"You won!"]
cWord = "RING"
cGuessed = ""
nWrong = 0
for cLetter in ["A","B","C","D","E","F"]
letter(cLetter)
next
aChecks + ["six mistakes lose",oInfo.getText(),"You lost. The word was RING"]
return aChecks
Image Viewer
An image viewer: a picture is drawn at the start (or opened from a file) and changed by Java2D operations: grayscale, invert, flip, half size.
cd samples/UsingJava/applications/ImageViewer then ring ImageViewer.ringSource code
# An image viewer: a picture is drawn at the start (or opened from a file) and changed by Java2D operations: grayscale, invert, flip, half size.
load "java.ring"
using {
"java.awt"
"java.awt.color"
"java.awt.image"
}
oOriginal = NULL
oImage = NULL
oWin = jWindow("Image viewer",560,460)
oPicture = jLabel("")
oGray = jButton("Grayscale","onGray")
oInvert = jButton("Invert","onInvert")
oFlip = jButton("Flip","onFlip")
oHalf = jButton("Half size","onHalf")
oReset = jButton("Reset","onReset")
oOpen = jButton("Open...","onOpen")
oStatus = jLabel(" ")
oWin.add([jBorder(
jScroll(oPicture),
jPad(jRow([oOpen,oGray,oInvert,oFlip,oHalf,oReset],6),6),
jPad(oStatus,4),
NULL,
NULL
),"Center"])
oOriginal = makePicture()
oImage = oOriginal
show()
jShow(oWin)
jAutoClose()
jMainLoop()
# a picture that is made with Java2D: a gradient from red to blue and a yellow circle
func makePicture
oNew = (new BufferedImage).@New([240,160,1])
oG = oNew.createGraphics()
for nX = 0 to 239
oG.setColor(jColor(255 - floor(nX * 255 / 239),0,floor(nX * 255 / 239)))
oG.fillRect(nX,0,1,160)
next
oG.setColor(jColor(255,220,0))
oG.fillOval(80,40,80,80)
oG.dispose()
return oNew
func show
oPicture.setIcon(new ImageIcon(oImage))
oStatus.setText(" " + oImage.getWidth() + " x " + oImage.getHeight())
func onGray aArgs
oOp = (new ColorConvertOp).@New([jStatic("java.awt.color.ColorSpace","getInstance",[1003]),NULL])
oImage = copyOf(oOp.filter(oImage,NULL))
show()
func onInvert aArgs
oOp = (new RescaleOp).@New([-1,255,NULL])
oImage = copyOf(oOp.filter(oImage,NULL))
show()
func onFlip aArgs
nWidth = oImage.getWidth()
nHeight = oImage.getHeight()
oNew = (new BufferedImage).@New([nWidth,nHeight,1])
oG = oNew.createGraphics()
oG.drawImage([oImage,nWidth,0,-nWidth,nHeight,NULL])
oG.dispose()
oImage = oNew
show()
func onHalf aArgs
nWidth = floor(oImage.getWidth() / 2)
nHeight = floor(oImage.getHeight() / 2)
if nWidth < 1 or nHeight < 1 # a picture of one pixel cannot get smaller (a size of 0 is an error)
return
ok
oNew = (new BufferedImage).@New([nWidth,nHeight,1])
oG = oNew.createGraphics()
oG.setRenderingHint(jGetStatic("java.awt.RenderingHints","KEY_INTERPOLATION"),jGetStatic("java.awt.RenderingHints","VALUE_INTERPOLATION_BILINEAR"))
oG.drawImage([oImage,0,0,nWidth,nHeight,NULL])
oG.dispose()
oImage = oNew
show()
func onReset aArgs
oImage = oOriginal
show()
func onOpen aArgs
cName = jOpenFile("Open a picture")
if cName != ""
oRead = jStatic("javax.imageio.ImageIO","read",[jNew("java.io.File",[cName])])
if not isnull(oRead)
oOriginal = copyOf(oRead)
oImage = oOriginal
show()
ok
ok
# a copy of any image as an RGB image
func copyOf oSource
nWidth = oSource.getWidth()
nHeight = oSource.getHeight()
oNew = (new BufferedImage).@New([nWidth,nHeight,1])
oG = oNew.createGraphics()
oG.drawImage([oSource,0,0,NULL])
oG.dispose()
return oNew
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
aChecks + ["the first pixel",oImage.getRGB([0,0]) & 16777215,16711680]
oInvert.doClick()
aChecks + ["Invert",oImage.getRGB([0,0]) & 16777215,65535]
oReset.doClick()
oFlip.doClick()
aChecks + ["Flip",oImage.getRGB([239,0]) & 16777215,16711680]
oReset.doClick()
oHalf.doClick()
aChecks + ["Half the size",oImage.getWidth(),120]
oReset.doClick()
oGray.doClick()
nPixel = oImage.getRGB([0,0]) & 16777215
aChecks + ["Grey has equal channels",floor(nPixel / 65536) = floor(nPixel / 256) % 256,1]
return aChecks
Julian Day
Julian day converter: dates and Julian day numbers in both directions.
cd samples/UsingJava/applications/JulianDay then ring JulianDay.ringSource code
# Julian day converter: dates and Julian day numbers in both directions.
load "java.ring"
using {
"javax.swing"
"java.awt"
}
oFrame = new JFrame("Julian day")
oFrame.setDefaultCloseOperation(2)
oToday = jStatic("java.time.LocalDate","now",[])
oYear = new JSpinner((new SpinnerNumberModel).@New([oToday.getYear(),-4713,9999,1]))
oMonth = new JSpinner((new SpinnerNumberModel).@New([oToday.getMonthValue(),1,12,1]))
oDay = new JSpinner((new SpinnerNumberModel).@New([oToday.getDayOfMonth(),1,31,1]))
oJulian = new JTextField("")
oToDate = new JButton("To date")
oToDate.addActionListener("onToDate")
oInfo = new JLabel(" ")
oInfo.setVerticalAlignment(1)
oDatePanel = new JPanel
oDatePanel.add(new JLabel("Date (year, month, day)"))
oDatePanel.add(oYear)
oDatePanel.add(oMonth)
oDatePanel.add(oDay)
oJulianPanel = new JPanel
oJulianPanel.add(new JLabel("Julian day"))
oJulian.setColumns(12)
oJulianPanel.add(oJulian)
oJulianPanel.add(oToDate)
oTop = new JPanel((new GridLayout).@New([2,1,0,0]))
oTop.add(oDatePanel)
oTop.add(oJulianPanel)
oFrame.add([oTop,"North"])
oFrame.add([oInfo,"Center"])
oFrame.setSize([480,260])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
for oSpinner in [oYear,oMonth,oDay]
oSpinner.addChangeListener("onDate")
next
fromDate()
jAutoClose()
jMainLoop()
# Julian day number of a calendar date (at noon)
func julianDay nYear, nMonth, nDay
nA = floor((14 - nMonth) / 12)
nY = nYear + 4800 - nA
nM = nMonth + 12 * nA - 3
return nDay + floor((153 * nM + 2) / 5) + 365 * nY + floor(nY / 4) - floor(nY / 100) + floor(nY / 400) - 32045
# the calendar date of a Julian day number: [year, month, day]
func calendarDate nJulian
nA = nJulian + 32044
nB = floor((4 * nA + 3) / 146097)
nC = nA - floor(146097 * nB / 4)
nD = floor((4 * nC + 3) / 1461)
nE = nC - floor(1461 * nD / 4)
nM = floor((5 * nE + 2) / 153)
nDay = nE - floor((153 * nM + 2) / 5) + 1
nMonth = nM + 3 - 12 * floor(nM / 10)
nYear = 100 * nB + nD - 4800 + floor(nM / 10)
return [nYear,nMonth,nDay]
func onDate aArgs
fromDate()
func onToDate aArgs
fromJulian()
func fromDate
nYear = floor(0 + oYear.getValue())
nMonth = floor(0 + oMonth.getValue())
nDay = floor(0 + oDay.getValue())
try
oDate = jStatic("java.time.LocalDate","of",[nYear,nMonth,nDay])
catch
oInfo.setText(" This date does not exist")
return
done
nJulian = julianDay(nYear,nMonth,nDay)
oJulian.setText("" + nJulian)
oInfo.setText("<html> " + oDate.getDayOfWeek().toString() + "<br> Modified Julian day: " + (nJulian - 2400001) + "<br> Day of the year: " + oDate.getDayOfYear() + "</html>")
# a Julian day the spinners can show: digits only, from day 0 (year -4713) to the last day of year 9999
func isJulianDay cText
if cText = "" or len(cText) > 8
return false
ok
for nPos = 1 to len(cText)
if not isdigit(cText[nPos])
return false
ok
next
return number(cText) <= julianDay(9999,12,31)
func fromJulian
cText = trim(oJulian.getText())
if not isJulianDay(cText)
oInfo.setText(" Enter a whole number from 0 to " + julianDay(9999,12,31))
return
ok
nJulian = number(cText)
aDate = calendarDate(nJulian)
oYear.setValue(aDate[1])
oMonth.setValue(aDate[2])
oDay.setValue(aDate[3])
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
aChecks + ["2000-01-01 is 2451545",julianDay(2000,1,1),2451545]
aChecks + ["and back",calendarDate(2451545)[1] * 10000 + calendarDate(2451545)[2] * 100 + calendarDate(2451545)[3],20000101]
oYear.setValue(2024)
oMonth.setValue(2)
oDay.setValue(29)
fromDate()
aChecks + ["the text field follows the date",oJulian.getText(),"2460370"]
aChecks + ["the weekday",substr(oInfo.getText(),"THURSDAY") > 0,true]
aChecks + ["day of the year",substr(oInfo.getText(),"Day of the year: 60") > 0,true]
oJulian.setText("2451545")
oToDate.doClick()
aChecks + ["to date: year",floor(0 + oYear.getValue()),2000]
aChecks + ["to date: month",floor(0 + oMonth.getValue()),1]
aChecks + ["to date: day",floor(0 + oDay.getValue()),1]
oMonth.setValue(2)
oDay.setValue(30)
fromDate()
aChecks + ["a date that does not exist",trim(oInfo.getText()),"This date does not exist"]
for cText in ["abc","","-5","2451545.7","99999999999","1e30","12 34"]
oJulian.setText(cText)
oToDate.doClick()
aChecks + ["not a Julian day: " + cText,left(trim(oInfo.getText()),14),"Enter a whole "]
next
aChecks + ["the date is not changed",floor(0 + oYear.getValue()),2000]
oJulian.setText("0")
oToDate.doClick()
aChecks + ["day 0 is year -4713",floor(0 + oYear.getValue()),-4713]
return aChecks
Lights Out
Lights Out: press a cell to toggle it and its neighbours until all the lights are off.
cd samples/UsingJava/applications/LightsOut then ring LightsOut.ringSource code
# Lights Out: press a cell to toggle it and its neighbours until all the lights are off.
load "java.ring"
using {
"javax.swing"
"java.awt"
}
C_SIZE = 5
aLights = list(C_SIZE * C_SIZE)
aCells = []
nPresses = 0
oFrame = new JFrame("Lights Out")
oFrame.setDefaultCloseOperation(2)
oGrid = new JPanel((new GridLayout).@New([C_SIZE,C_SIZE,4,4]))
oGrid.setBorder(jStatic("javax.swing.BorderFactory","createEmptyBorder",[8,8,8,8]))
for nCell = 1 to C_SIZE * C_SIZE
oCell = new JButton("")
oCell.setContentAreaFilled(false) # first: it turns opaque off, so setOpaque comes after it
oCell.setOpaque(true)
oCell.setFocusable(false)
oCell.setActionCommand("" + nCell)
oCell.addActionListener("onCell")
aCells + oCell
oGrid.add(oCell)
next
oInfo = new JLabel("")
oNew = new JButton("New game")
oNew.addActionListener("onNew")
oSouth = new JPanel(new BorderLayout)
oSouth.add([oInfo,"Center"])
oSouth.add([oNew,"East"])
oFrame.add([oGrid,"Center"])
oFrame.add([oSouth,"South"])
oFrame.setSize([340,400])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
newGame()
jAutoClose()
jMainLoop()
func lightsOn
nOn = 0
for nLight in aLights
nOn += nLight
next
return nOn
func showLights
for nCell = 1 to len(aLights)
if aLights[nCell]
aCells[nCell].setBackground(jColor(255,200,0))
else
aCells[nCell].setBackground(jColor(90,90,90))
ok
next
nOn = lightsOn()
if nOn = 0
oInfo.setText("All lights are off - you won in " + nPresses + " presses!")
else
oInfo.setText("" + nOn + " lights on, presses: " + nPresses)
ok
func toggle nCell
aLights[nCell] = not aLights[nCell]
# toggle the cell and its neighbours
func flip nCell
nRow = floor((nCell - 1) / C_SIZE)
nCol = (nCell - 1) % C_SIZE
toggle(nCell)
if nRow > 0 toggle(nCell - C_SIZE) ok
if nRow < C_SIZE - 1 toggle(nCell + C_SIZE) ok
if nCol > 0 toggle(nCell - 1) ok
if nCol < C_SIZE - 1 toggle(nCell + 1) ok
func onCell aArgs
flip(0 + aArgs[1].getActionCommand())
nPresses++
showLights()
func onNew aArgs
newGame()
func newGame
aLights = list(C_SIZE * C_SIZE)
while lightsOn() = 0 # random presses keep the game solvable; they can cancel each other, so press again
for nStep = 1 to 12
flip(random(C_SIZE * C_SIZE - 1) + 1)
next
end
nPresses = 0
showLights()
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
aLights = list(C_SIZE * C_SIZE)
nPresses = 0
aCells[13].doClick()
aChecks + ["a press in the middle turns on five lights",lightsOn(),5]
aCells[13].doClick()
aChecks + ["the same press turns them off",lightsOn(),0]
aChecks + ["the message",left(oInfo.getText(),23),"All lights are off - yo"]
aCells[1].doClick()
aChecks + ["a corner turns on three lights",lightsOn(),3]
aChecks + ["a lit cell is gold",aCells[1].getBackground().getRed(),255]
aChecks + ["an unlit cell is gray",aCells[25].getBackground().getRed(),90]
return aChecks
Loan Calculator
Loan calculator: the monthly payment, the total interest and the first year of the amortization table.
cd samples/UsingJava/applications/LoanCalculator then ring LoanCalculator.ringSource code
# Loan calculator: the monthly payment, the total interest and the first year of the amortization table.
load "java.ring"
using {
"javax.swing"
"javax.swing.table"
"java.awt"
}
oFrame = new JFrame("Loan calculator")
oFrame.setDefaultCloseOperation(2)
oAmount = new JTextField("20000")
oRate = new JTextField("6")
oYears = new JTextField("5")
oCalc = new JButton("Calculate")
oCalc.addActionListener("onCalculate")
oForm = new JPanel((new GridLayout).@New([4,2,6,6]))
oForm.add(new JLabel("Loan amount"))
oForm.add(oAmount)
oForm.add(new JLabel("Interest % / year"))
oForm.add(oRate)
oForm.add(new JLabel("Years"))
oForm.add(oYears)
oForm.add(new JLabel(""))
oForm.add(oCalc)
oPayment = new JLabel(" ")
oPayment.setFont((new Font).@New(["SansSerif",1,14]))
oInterest = new JLabel(" ")
oTotal = new JLabel(" ")
oSums = new JPanel((new GridLayout).@New([3,1,2,2]))
oSums.add(oPayment)
oSums.add(oInterest)
oSums.add(oTotal)
oTop = new JPanel((new GridLayout).@New([1,2,16,0]))
oTop.setBorder(jStatic("javax.swing.BorderFactory","createEmptyBorder",[10,10,10,10]))
oTop.add(oForm)
oTop.add(oSums)
oModel = (new DefaultTableModel).@New([jArray("java.lang.String",["Month","Payment","Interest","Principal","Balance"]),0])
oTable = new JTable(oModel)
oFrame.add([oTop,"North"])
oFrame.add([new JScrollPane(oTable),"Center"])
oFrame.setSize([640,480])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
calculate()
jAutoClose()
jMainLoop()
# a number with two decimals
func money nValue
nCents = floor(nValue * 100 + 0.5)
cText = "" + floor(nCents / 100) + "."
nRest = nCents % 100
if nRest < 10
cText += "0"
ok
return cText + floor(nRest)
# the monthly payment of a loan
func monthlyPayment nAmount, nYearlyRate, nYears
nMonths = nYears * 12
nMonthlyRate = nYearlyRate / 100 / 12
if nMonthlyRate = 0
return nAmount / nMonths
ok
return nAmount * nMonthlyRate / (1 - pow(1 + nMonthlyRate,-nMonths))
func onCalculate aArgs
calculate()
func calculate
nAmount = number(oAmount.getText())
nRate = number(oRate.getText())
nYears = number(oYears.getText())
oModel.setRowCount(0)
if nAmount <= 0 or nYears <= 0 or nRate < 0
oPayment.setText("Check the input")
oInterest.setText(" ")
oTotal.setText(" ")
return
ok
nPayment = monthlyPayment(nAmount,nRate,nYears)
nMonths = floor(nYears * 12)
nBalance = nAmount
nTotalInterest = 0
for nMonth = 1 to nMonths
nInterestPart = nBalance * nRate / 100 / 12
nPrincipal = nPayment - nInterestPart
nBalance -= nPrincipal
nTotalInterest += nInterestPart
if nMonth <= 12
oModel.addRow(jArray("java.lang.Object",["" + nMonth,money(nPayment),money(nInterestPart),money(nPrincipal),money(fabs(nBalance))]))
ok
next
oPayment.setText("Monthly payment: " + money(nPayment))
oInterest.setText("Total interest: " + money(nTotalInterest))
oTotal.setText("Total paid: " + money(nAmount + nTotalInterest))
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
aChecks + ["20000 at 6% for 5 years",oPayment.getText(),"Monthly payment: 386.66"]
aChecks + ["total interest",oInterest.getText(),"Total interest: 3199.36"]
aChecks + ["twelve rows",oModel.getRowCount(),12]
aChecks + ["the first month: interest",oModel.getValueAt(0,2),"100.00"]
oRate.setText("0")
oAmount.setText("1200")
oYears.setText("1")
oCalc.doClick()
aChecks + ["no interest",oPayment.getText(),"Monthly payment: 100.00"]
oYears.setText("0")
oCalc.doClick()
aChecks + ["bad input",oPayment.getText(),"Check the input"]
aChecks + ["and no rows",oModel.getRowCount(),0]
aChecks + ["money rounds",money(2.005 + 0.001),"2.01"]
return aChecks
Log Analyzer
A log analyzer: jQuery counts and filters the lines of a log file (a sample log is made at the start; "Open..." reads another one).
cd samples/UsingJava/applications/LogAnalyzer then ring LogAnalyzer.ringSource code
# A log analyzer: jQuery counts and filters the lines of a log file (a sample log is made at the start; "Open..." reads another one).
load "java.ring"
using {
"javax.swing.table"
}
aLevels = ["INFO","WARN","ERROR"]
aSources = ["db","web","auth"]
cFile = jProperty("java.io.tmpdir") + "/ringjava_sample.log"
makeSampleLog(cFile)
aEntries = []
oWin = jWindow("Log analyzer",720,480)
oLevel = jCombo(["All levels","INFO","WARN","ERROR"],"onRefresh")
oSearch = jField("",16,"onRefresh")
oOpen = jButton("Open...","onOpen")
oModel = (new DefaultTableModel).@New([jArray("java.lang.String",["Time","Level","Source","Message"]),0])
oTable = new JTable(oModel)
oSummary = jLabel(" ")
oFile = jLabel(" ")
oWin.add([jBorder(
jScroll(oTable),
jPad(jRow([jLabel("Level"),oLevel,jLabel("Message contains"),oSearch,oOpen],6),6),
jPad(jColumn([oSummary,oFile],4),6),
NULL,
NULL
),"Center"])
loadFile(cFile)
jShow(oWin)
jAutoClose()
jMainLoop()
func makeSampleLog cName
aLines = []
for nAt = 0 to 59
cLevel = aLevels[(nAt * 7) % 5 % 3 + 1]
cSource = aSources[nAt % 3 + 1]
cTime = "12:" + right("0" + floor(nAt / 2),2) + ":" + right("0" + (nAt % 2) * 30,2)
aLines + ("2024-05-01 " + cTime + " " + cLevel + " [" + cSource + "] message number " + nAt)
next
write(cName,jQuery(aLines).join(nl))
# every line is "date time LEVEL [source] message": a list [time, level, source, message]
func loadFile cName
aEntries = []
for cLine in str2list(substr(read(cName),char(13),""))
aParts = str2list(substr(cLine," ",nl))
if len(aParts) >= 5 and left(aParts[4],1) = "["
cMessage = ""
for nAt = 5 to len(aParts)
cMessage += aParts[nAt] + " "
next
aEntries + [aParts[2],aParts[3],substr(aParts[4],2,len(aParts[4]) - 2),trim(cMessage)]
ok
next
oFile.setText(" " + cName)
refresh()
func refresh
oQuery = jQuery(aEntries)
if oLevel.getSelectedIndex() > 0
oQuery = oQuery.filter("x[2] = '" + oLevel.getSelectedItem() + "'")
ok
cText = trim(oSearch.getText())
if cText != ""
oQuery = oQuery.filter("substr(x[4],'" + quoted(cText) + "') > 0")
ok
aShown = oQuery.toList()
oModel.setRowCount(0)
for aEntry in aShown
oModel.addRow(jArray("java.lang.Object",aEntry))
next
aCounts = jQuery(aEntries).groupBy("x[2]").map("x[1] + ' ' + len(x[2])").toList()
oSummary.setText(" " + len(aShown) + " of " + len(aEntries) + " lines (" + jQuery(aCounts).join(", ") + ")")
# a text inside the quotes of a query: a quote in it would end the text early and the query would be an error
func quoted cText
return substr(cText,"'","' + char(39) + '")
func onRefresh aArgs
refresh()
func onOpen aArgs
cName = jOpenFile("Open a log file")
if cName != ""
loadFile(cName)
ok
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
aChecks + ["the entries",len(aEntries),60]
oLevel.setSelectedIndex(3)
refresh()
aChecks + ["one level",oModel.getRowCount(),12]
oSearch.setText("number 5")
refresh()
aChecks + ["a search in a level",oModel.getRowCount(),2]
aChecks + ["the first entry",aEntries[1][1],"12:00:00"]
oSearch.setText("it's")
refresh()
aChecks + ["a quote in the search is not an error",oModel.getRowCount(),0]
oSearch.setText("")
return aChecks
Login Form
Login form: validation, a SHA-256 hash of the password and a limit of three attempts.
cd samples/UsingJava/applications/LoginForm then ring LoginForm.ringSource code
# Login form: validation, a SHA-256 hash of the password and a limit of three attempts.
load "java.ring"
using {
"javax.swing"
"java.awt"
}
# the "database": user name -> SHA-256 hash of the password
aUsers = []
nAttempts = 0
oFrame = new JFrame("Sign in")
oFrame.setDefaultCloseOperation(2)
oUser = new JTextField("")
oPassword = new JPasswordField("")
oShow = new JCheckBox("Show password")
oSignIn = new JButton("Sign in")
oRegister = new JButton("Register")
oMessage = new JLabel(" ")
oShow.addActionListener("onShow")
oSignIn.addActionListener("onSignIn")
oRegister.addActionListener("onRegister")
oForm = new JPanel((new GridLayout).@New([4,2,8,8]))
oForm.setBorder(jStatic("javax.swing.BorderFactory","createEmptyBorder",[14,14,4,14]))
oForm.add(new JLabel("User name"))
oForm.add(oUser)
oForm.add(new JLabel("Password"))
oForm.add(oPassword)
oForm.add(new JLabel(""))
oForm.add(oShow)
oForm.add(oSignIn)
oForm.add(oRegister)
oMessage.setBorder(jStatic("javax.swing.BorderFactory","createEmptyBorder",[4,14,10,14]))
oFrame.add([oForm,"Center"])
oFrame.add([oMessage,"South"])
oFrame.getRootPane().setDefaultButton(oSignIn)
oFrame.setSize([380,240])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
register("admin","secret")
jAutoClose()
jMainLoop()
# the SHA-256 hash of a text, in hexadecimal
func hashOf cPassword
oDigest = jStatic("java.security.MessageDigest","getInstance",["SHA-256"])
oBytes = oDigest.@digest(cPassword)
cHex = ""
for nPos = 1 to len(oBytes) # a byte[] arrives as a Ring text of raw bytes
nByte = ascii(oBytes[nPos])
cPair = lower(hex(nByte))
if len(cPair) < 2
cPair = "0" + cPair
ok
cHex += cPair
next
return cHex
func register cName, cPassword
for aUser in aUsers
if aUser[1] = lower(cName)
return false
ok
next
aUsers + [lower(cName),hashOf(cPassword)]
return true
func checkLogin cName, cPassword
for aUser in aUsers
if aUser[1] = lower(cName) and aUser[2] = hashOf(cPassword)
return true
ok
next
return false
func onShow aArgs
if oShow.isSelected()
oPassword.setEchoChar(0)
else
oPassword.setEchoChar(jChar("*"))
ok
func passwordText
return oPassword.getText()
# true when the fields are filled; an empty field gets a red border
func validate
lValid = true
for aField in [[oUser,trim(oUser.getText())],[oPassword,passwordText()]]
if aField[2] = ""
aField[1].setBorder(jStatic("javax.swing.BorderFactory","createLineBorder",[jColor(220,0,0)]))
lValid = false
else
aField[1].setBorder(jStatic("javax.swing.BorderFactory","createLineBorder",[jColor(150,150,150)]))
ok
next
return lValid
func onSignIn aArgs
signIn()
func signIn
if not validate()
oMessage.setForeground(jColor(178,34,34))
oMessage.setText("Please fill in both fields")
return
ok
nAttempts++
if checkLogin(oUser.getText(),passwordText())
oMessage.setForeground(jColor(0,100,0))
oMessage.setText("Welcome, " + oUser.getText() + "!")
nAttempts = 0
else
oMessage.setForeground(jColor(178,34,34))
oMessage.setText("Wrong user name or password (attempt " + nAttempts + " of 3)")
if nAttempts >= 3
oSignIn.setEnabled(false)
oMessage.setText("Too many attempts: sign in is disabled")
ok
ok
func onRegister aArgs
if validate()
if register(oUser.getText(),passwordText())
oMessage.setForeground(jColor(0,100,0))
oMessage.setText("User " + oUser.getText() + " created")
else
oMessage.setForeground(jColor(178,34,34))
oMessage.setText("That user name is taken")
ok
ok
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
aChecks + ["the SHA-256 of abc",hashOf("abc"),"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"]
aChecks + ["the admin exists",checkLogin("ADMIN","secret"),true]
aChecks + ["a wrong password",checkLogin("admin","nope"),false]
oSignIn.doClick()
aChecks + ["empty fields",oMessage.getText(),"Please fill in both fields"]
oUser.setText("admin")
oPassword.setText("secret")
oSignIn.doClick()
aChecks + ["a good login",oMessage.getText(),"Welcome, admin!"]
oPassword.setText("bad")
oSignIn.doClick()
aChecks + ["a bad login",left(oMessage.getText(),5),"Wrong"]
oSignIn.doClick()
oSignIn.doClick()
aChecks + ["three attempts lock it",oSignIn.isEnabled(),false]
oUser.setText("Ann")
oPassword.setText("pw")
oRegister.doClick()
aChecks + ["register",oMessage.getText(),"User Ann created"]
oRegister.doClick()
aChecks + ["a name that is taken",oMessage.getText(),"That user name is taken"]
aChecks + ["the new user can sign in",checkLogin("ann","pw"),true]
return aChecks
Memory Game
A memory game: find the pairs. A Swing timer turns two different cards back.
cd samples/UsingJava/applications/MemoryGame then ring MemoryGame.ringSource code
# A memory game: find the pairs. A Swing timer turns two different cards back.
load "java.ring"
using {
"javax.swing"
"java.awt"
}
aSymbols = ["A","B","C","D","E","F","G","H"]
aCards = [] # the symbol of each card
aButtons = []
aOpen = [] # the cards that are turned now
nFound = 0
nMoves = 0
lBusy = false
oFrame = new JFrame("Memory")
oFrame.setDefaultCloseOperation(2)
oGrid = new JPanel((new GridLayout).@New([4,4,6,6]))
oGrid.setBorder(jStatic("javax.swing.BorderFactory","createEmptyBorder",[8,8,8,8]))
oStatus = new JLabel("Find the 8 pairs")
oStatus.setHorizontalAlignment(0)
oNew = new JButton("New game")
oNew.addActionListener("onNew")
for nI = 1 to 16
oButton = new JButton("?")
oButton.setFont((new Font).@New(["SansSerif",1,28]))
oButton.setActionCommand("" + nI)
oButton.addActionListener("onCard")
aButtons + oButton
oGrid.add(oButton)
next
oSouth = new JPanel(new BorderLayout)
oSouth.add([oStatus,"Center"])
oSouth.add([oNew,"East"])
oFrame.add([oGrid,"Center"])
oFrame.add([oSouth,"South"])
oFrame.setSize([360,420])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
oHide = jTimer(700,"onHide")
oHide.setRepeats(false)
shuffleCards()
jAutoClose()
jMainLoop()
func shuffleCards
oHide.stop() # a pending turn back must not hide a card of the new game
aCards = []
for cSymbol in aSymbols
aCards + cSymbol
aCards + cSymbol
next
for nI = len(aCards) to 2 step -1 # Fisher-Yates
nJ = 1 + random(nI - 1)
cTemp = aCards[nI]
aCards[nI] = aCards[nJ]
aCards[nJ] = cTemp
next
for oButton in aButtons
oButton.setText("?")
oButton.setEnabled(true)
next
aOpen = []
nFound = 0
nMoves = 0
lBusy = false
oStatus.setText("Find the 8 pairs")
func onNew aArgs
shuffleCards()
func onCard aArgs
nCard = 0 + aArgs[1].getActionCommand()
if lBusy or find(aOpen,nCard) > 0
return
ok
aButtons[nCard].setText(aCards[nCard])
aOpen + nCard
if len(aOpen) = 2
nMoves++
if aCards[aOpen[1]] = aCards[aOpen[2]]
aButtons[aOpen[1]].setEnabled(false)
aButtons[aOpen[2]].setEnabled(false)
aOpen = []
nFound++
if nFound = 8
oStatus.setText("Done in " + nMoves + " moves!")
else
oStatus.setText("Found " + nFound + " pairs, " + nMoves + " moves")
ok
else
lBusy = true
oHide.start()
ok
ok
func onHide aArgs
for nCard in aOpen
aButtons[nCard].setText("?")
next
aOpen = []
lBusy = false
oStatus.setText("Found " + nFound + " pairs, " + nMoves + " moves")
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
nB = 0
for n = 2 to 16
if aCards[n] = aCards[1]
nB = n
ok
next
aButtons[1].doClick()
aButtons[nB].doClick()
aChecks + ["a pair found",nFound,1]
oNew.doClick()
aChecks + ["New game",nFound,0]
return aChecks
Minesweeper
Minesweeper: a 9 x 9 grid of buttons, 10 mines. Click a cell to open it (an empty cell opens its neighbours); the "Flag" box marks a mine instead of opening.
cd samples/UsingJava/applications/Minesweeper then ring Minesweeper.ringSource code
# Minesweeper: a 9 x 9 grid of buttons, 10 mines. Click a cell to open it (an empty cell opens its neighbours); the "Flag" box marks a mine instead of opening.
load "java.ring"
nSize = 9
nMines = 10
aMine = []
aShown = []
aFlag = []
aButtons = []
lOver = false
nOpened = 0
oWin = jWindow("Minesweeper",420,480)
oFlag = jCheck("Flag",false,"")
oNew = jButton("New game","onNew")
oStatus = jLabel(" ")
for nAt = 1 to nSize * nSize
oButton = jButton(" ","onCell")
oButton.setActionCommand("" + nAt)
oButton.setMargin(jNew("java.awt.Insets",[0,0,0,0]))
aButtons + oButton
next
oWin.add([jBorder(
jGrid(nSize,nSize,aButtons,1),
jPad(jRow([oNew,oFlag,oStatus],10),6),
NULL,
NULL,
NULL
),"Center"])
newGame()
jShow(oWin)
jAutoClose()
jMainLoop()
func newGame
lOver = false
nOpened = 0
aMine = list(nSize * nSize)
aShown = list(nSize * nSize)
aFlag = list(nSize * nSize)
for nAt = 1 to nSize * nSize
aMine[nAt] = 0
aShown[nAt] = 0
aFlag[nAt] = 0
aButtons[nAt].setText(" ")
aButtons[nAt].setEnabled(true)
next
nPlaced = 0
while nPlaced < nMines
nAt = random(nSize * nSize - 1) + 1
if aMine[nAt] = 0
aMine[nAt] = 1
nPlaced++
ok
end
oStatus.setText("Mines: " + nMines)
# the cells around a cell: a list of numbers
func around nAt
nRow = floor((nAt - 1) / nSize)
nCol = (nAt - 1) % nSize
aOut = []
for nDy = -1 to 1
for nDx = -1 to 1
if nDx != 0 or nDy != 0
nR = nRow + nDy
nC = nCol + nDx
if nR >= 0 and nR < nSize and nC >= 0 and nC < nSize
aOut + (nR * nSize + nC + 1)
ok
ok
next
next
return aOut
func mineCount nAt
nCount = 0
for nOther in around(nAt)
nCount += aMine[nOther]
next
return nCount
func openCell nAt
if aShown[nAt] = 1 or aFlag[nAt] = 1
return
ok
aShown[nAt] = 1
nOpened++
nCount = mineCount(nAt)
aButtons[nAt].setEnabled(false)
if nCount > 0
aButtons[nAt].setText("" + nCount)
else
for nOther in around(nAt)
openCell(nOther)
next
ok
func onCell aArgs
if lOver
return
ok
nAt = 0 + aArgs[1].getActionCommand()
if oFlag.isSelected()
if aShown[nAt] = 0
aFlag[nAt] = 1 - aFlag[nAt]
if aFlag[nAt] = 1
aButtons[nAt].setText("F")
else
aButtons[nAt].setText(" ")
ok
ok
return
ok
if aFlag[nAt] = 1
return
ok
if aMine[nAt] = 1
lOver = true
for nCell = 1 to nSize * nSize
if aMine[nCell] = 1
aButtons[nCell].setText("*")
ok
next
oStatus.setText("Game over")
return
ok
openCell(nAt)
if nOpened = nSize * nSize - nMines
lOver = true
oStatus.setText("You win!")
ok
func onNew aArgs
newGame()
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
nSafe = find(aMine,0)
aButtons[nSafe].doClick()
aChecks + ["a safe cell opens",nOpened > 0,1]
nMineAt = find(aMine,1)
oFlag.setSelected(true)
aButtons[nMineAt].doClick()
aChecks + ["a flag",aFlag[nMineAt],1]
oFlag.setSelected(false)
aButtons[nMineAt].doClick()
aChecks + ["a flagged cell does not open",oStatus.getText(),"Mines: 10"]
oFlag.setSelected(true)
aButtons[nMineAt].doClick()
oFlag.setSelected(false)
aButtons[nMineAt].doClick()
aChecks + ["a mine ends the game",oStatus.getText(),"Game over"]
oNew.doClick()
aChecks + ["New game",oStatus.getText(),"Mines: 10"]
return aChecks
Notepad
Notepad: a menu, a text area, and the open/save dialogs (JFileChooser) with Java file I/O.
cd samples/UsingJava/applications/Notepad then ring Notepad.ringSource code
# Notepad: a menu, a text area, and the open/save dialogs (JFileChooser) with Java file I/O.
load "java.ring"
using {
"javax.swing"
"java.awt"
"java.awt.event"
"java.io"
"java.nio.file"
"java.nio.charset"
}
Files = new Files
StandardCharsets = new StandardCharsets
cFile = ""
lChanged = false
oFrame = new JFrame("Notepad - untitled")
oFrame.setDefaultCloseOperation(2)
oText = new JTextArea
oText.setFont((new Font).@New(["Monospaced",0,14]))
oStatus = new JLabel(" Ready")
oMenuBar = new JMenuBar
oFile = new JMenu("File")
for aItem in [["New","onNew"],["Open...","onOpen"],["Save","onSave"],["Save as...","onSaveAs"],["Exit","onExit"]]
oItem = new JMenuItem(aItem[1])
oItem.addActionListener(aItem[2])
oFile.add(oItem)
next
oMenuBar.add(oFile)
oFrame.setJMenuBar(oMenuBar)
oFrame.add([new JScrollPane(oText),"Center"])
oFrame.add([oStatus,"South"])
oFrame.setSize([520,380])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
oText.getDocument().addDocumentListener("onEdit")
jAutoClose()
jMainLoop()
func onEdit aArgs
lChanged = true
oStatus.setText(" " + len(oText.getText()) + " characters, " + oText.getLineCount() + " lines")
func title
cName = "untitled"
if cFile != ""
cName = (new File).@New([cFile]).getName()
ok
oFrame.setTitle("Notepad - " + cName)
# true when nothing would be lost: no changes, or the user agrees to drop them
func discardOk
return (not lChanged) or jConfirm("Discard the changes?","Notepad")
func onNew aArgs
if not discardOk()
return
ok
oText.setText("")
cFile = ""
lChanged = false
title()
func onOpen aArgs
if not discardOk()
return
ok
oChooser = new JFileChooser
if oChooser.showOpenDialog(oFrame) = 0
openFile(oChooser.getSelectedFile().getAbsolutePath())
ok
func openFile cPath
cFile = cPath
oPath = (new File).@New([cFile]).toPath()
oText.setText((new String).@New([Files.readAllBytes(oPath),StandardCharsets.UTF_8]).toString())
lChanged = false
title()
func onSave aArgs
if cFile = ""
return onSaveAs(aArgs)
ok
saveFile()
func saveFile
oPath = (new File).@New([cFile]).toPath()
Files.write([oPath,(new String(oText.getText())).@getBytes(StandardCharsets.UTF_8),jArray("java.nio.file.OpenOption",[])])
lChanged = false
oStatus.setText(" Saved " + cFile)
func onSaveAs aArgs
oChooser = new JFileChooser
if oChooser.showSaveDialog(oFrame) = 0
cFile = oChooser.getSelectedFile().getAbsolutePath()
title()
saveFile()
ok
func onExit aArgs
if not discardOk()
return
ok
oFrame.dispose()
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
cFile = currentdir() + "/_note.txt"
oText.setText("hello")
saveFile()
oText.setText("")
openFile(cFile)
aChecks + ["save and open a file",oText.getText(),"hello"]
remove(cFile)
return aChecks
Number Guess
Guess the number between 1 and 100: higher/lower hints and a list of the guesses.
cd samples/UsingJava/applications/NumberGuess then ring NumberGuess.ringSource code
# Guess the number between 1 and 100: higher/lower hints and a list of the guesses.
load "java.ring"
using {
"javax.swing"
"java.awt"
}
nSecret = 0
nAttempts = 0
lWon = false # the number was found: more guesses are ignored
nBest = 0
oFrame = new JFrame("Guess the number")
oFrame.setDefaultCloseOperation(2)
oGuess = new JSpinner((new SpinnerNumberModel).@New([50,1,100,1]))
oGuessButton = new JButton("Guess")
oNew = new JButton("New game")
oGuessButton.addActionListener("onGuess")
oNew.addActionListener("onNew")
oBar = new JPanel
oBar.add(new JLabel("I am thinking of a number between 1 and 100:"))
oBar.add(oGuess)
oBar.add(oGuessButton)
oBar.add(oNew)
oHint = new JLabel("")
oHint.setFont((new Font).@New(["SansSerif",1,15]))
oHint.setHorizontalAlignment(0)
oHistory = new DefaultListModel
oTop = new JPanel(new BorderLayout)
oTop.add([oBar,"North"])
oTop.add([oHint,"Center"])
oFrame.add([oTop,"North"])
oFrame.add([new JScrollPane(new JList(oHistory)),"Center"])
oFrame.setSize([420,320])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
newGame()
jAutoClose()
jMainLoop()
func onNew aArgs
newGame()
func onGuess aArgs
guess(floor(0 + oGuess.getValue()))
func newGame
nSecret = random(99) + 1
nAttempts = 0
lWon = false
oHint.setText("Take a guess")
oHistory.clear()
oGuess.setValue(50)
func guess nNumber
if lWon
return
ok
nAttempts++
if nNumber < nSecret
cResult = "too low"
but nNumber > nSecret
cResult = "too high"
else
cResult = "correct"
ok
oHistory.insertElementAt("" + nAttempts + ". " + nNumber + " is " + cResult,0)
if cResult = "correct"
lWon = true
oHint.setText("Yes! " + nNumber + " in " + nAttempts + " attempts")
if nBest = 0 or nAttempts < nBest
nBest = nAttempts
ok
else
oHint.setText("Try a number that is " + substr(cResult,"too ","") + "er")
ok
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
nSecret = 40
nAttempts = 0
oHistory.clear()
oGuess.setValue(10)
oGuessButton.doClick()
aChecks + ["too low",oHint.getText(),"Try a number that is lower"]
oGuess.setValue(90)
oGuessButton.doClick()
aChecks + ["too high",oHint.getText(),"Try a number that is higher"]
oGuess.setValue(40)
oGuessButton.doClick()
aChecks + ["correct",oHint.getText(),"Yes! 40 in 3 attempts"]
aChecks + ["three lines in the list",oHistory.getSize(),3]
aChecks + ["the best score",nBest,3]
oNew.doClick()
aChecks + ["new game",nAttempts,0]
aChecks + ["the secret is in range",nSecret >= 1 and nSecret <= 100,true]
return aChecks
Paint Board
A paint program on JCanvas: a pen, lines, rectangles and ovals, colours, a brush size, an eraser, clear and save as a PNG file.
cd samples/UsingJava/applications/PaintBoard then ring PaintBoard.ringSource code
# A paint program on JCanvas: a pen, lines, rectangles and ovals, colours, a brush size, an eraser, clear and save as a PNG file.
load "java.ring"
oWin = jWindow("Paint board",640,520)
oCanvas = new JCanvas(600,400)
oCanvas.lineWidth(3)
oCanvas.update()
cColour = "black"
nStartX = 0
nStartY = 0
nLastX = 0
nLastY = 0
lDown = false # true between a press and a release
oTool = jCombo(["Pen","Line","Rectangle","Oval","Eraser"],"")
oSize = jSlider(1,20,3,"onSize")
oClear = jButton("Clear","onClear")
oSave = jButton("Save...","onSave")
oStatus = jLabel(" ")
aBar = [jLabel("Tool"),oTool,jLabel("Size"),oSize]
aColourButtons = []
for cName in ["black","red","green","blue","orange"]
oButton = jButton(cName,"onColour")
aColourButtons + oButton
aBar + oButton
next
aBar + oClear
aBar + oSave
oWin.add([jBorder(jScroll(oCanvas.component()),jPad(jRow(aBar,6),4),jPad(oStatus,4),NULL,NULL),"Center"])
oCanvas.onPress("onPress")
oCanvas.onDrag("onDrag")
oCanvas.onRelease("onRelease")
jShow(oWin)
jAutoClose()
jMainLoop()
func onColour aArgs
cColour = aArgs[1].getActionCommand()
func onSize aArgs
oCanvas.lineWidth(oSize.getValue())
func onClear aArgs
oCanvas.clear("white")
oCanvas.update()
oStatus.setText("cleared")
func onSave aArgs
cFile = jSaveFile("Save the picture")
if cFile != ""
oCanvas.save(cFile)
oStatus.setText("saved " + cFile)
ok
func onPress nX, nY
lDown = true
nStartX = nX
nStartY = nY
nLastX = nX
nLastY = nY
func onDrag nX, nY
if not lDown # a drag whose press was missed (for example the click that activated the window): start the stroke here
onPress(nX,nY)
return
ok
cTool = oTool.getSelectedItem()
if cTool = "Pen"
oCanvas.color(cColour)
oCanvas.line(nLastX,nLastY,nX,nY)
oCanvas.update()
but cTool = "Eraser"
oCanvas.color("white")
oCanvas.line(nLastX,nLastY,nX,nY)
oCanvas.update()
ok
nLastX = nX
nLastY = nY
oStatus.setText(" " + nX + ", " + nY)
func onRelease nX, nY
if not lDown
return
ok
lDown = false
cTool = oTool.getSelectedItem()
nLeft = smaller(nStartX,nX)
nTop = smaller(nStartY,nY)
nWidth = fabs(nX - nStartX)
nHeight = fabs(nY - nStartY)
oCanvas.color(cColour)
if cTool = "Line"
oCanvas.line(nStartX,nStartY,nX,nY)
but cTool = "Rectangle"
oCanvas.rect(nLeft,nTop,nWidth,nHeight)
but cTool = "Oval"
oCanvas.oval(nLeft,nTop,nWidth,nHeight)
ok
oCanvas.update()
func smaller a, b
if a < b
return a
ok
return b
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
oTool.setSelectedIndex(2)
onPress(10,10)
onRelease(60,40)
aChecks + ["the rectangle outline",oCanvas.pixel(10,20),0]
aChecks + ["the inside is empty",oCanvas.pixel(30,30),16777215]
aColourButtons[2].doClick()
aChecks + ["a colour button",cColour,"red"]
oClear.doClick()
aChecks + ["Clear",oCanvas.pixel(10,20),16777215]
# a drag without its press (the click that activates the window) draws nothing: no line from the old position
oClear.doClick()
oTool.setSelectedIndex(0)
onRelease(0,0)
onDrag(300,300)
onDrag(310,300)
aChecks + ["no stray line before the first press",oCanvas.pixel(150,150),16777215]
aChecks + ["the stroke starts where the drag is",oCanvas.pixel(305,300),16711680]
onRelease(310,300)
onDrag(50,50)
aChecks + ["no stroke after the release",oCanvas.pixel(180,180),16777215]
return aChecks
Password Generator
A password generator: SecureRandom picks the characters, a slider the length, check boxes the kinds of characters.
cd samples/UsingJava/applications/PasswordGenerator then ring PasswordGenerator.ringSource code
# A password generator: SecureRandom picks the characters, a slider the length, check boxes the kinds of characters.
load "java.ring"
using {
"javax.swing"
"java.awt"
"java.awt.datatransfer"
"java.security"
}
oRandom = new SecureRandom
oFrame = new JFrame("Password generator")
oFrame.setDefaultCloseOperation(2)
oPanel = new JPanel
oPanel.setLayout((new BoxLayout).@New([oPanel,1]))
oPanel.setBorder(jStatic("javax.swing.BorderFactory","createEmptyBorder",[12,12,12,12]))
oPassword = new JTextField
oPassword.setFont((new Font).@New(["Monospaced",1,18]))
oPassword.setEditable(false)
oLength = (new JSlider).@New([6,40])
oLength.setValue(16)
oLengthLabel = new JLabel("Length: 16")
oLower = new JCheckBox("Lower case letters")
oUpper = new JCheckBox("Upper case letters")
oDigits = new JCheckBox("Digits")
oSymbols = new JCheckBox("Symbols")
oLower.setSelected(true)
oUpper.setSelected(true)
oDigits.setSelected(true)
oGenerate = new JButton("Generate")
oCopy = new JButton("Copy")
oButtons = new JPanel
oButtons.add(oGenerate)
oButtons.add(oCopy)
for oItem in [oPassword,oLengthLabel,oLength,oLower,oUpper,oDigits,oSymbols,oButtons]
oPanel.add(oItem)
next
oFrame.add(oPanel)
oFrame.setSize([380,330])
oFrame.setLocationRelativeTo(NULL)
oLength.addChangeListener("onLength")
oGenerate.addActionListener("onGenerate")
oCopy.addActionListener("onCopy")
oFrame.setVisible(true)
onGenerate(NULL)
jAutoClose()
jMainLoop()
func onLength aArgs
oLengthLabel.setText("Length: " + oLength.getValue())
func onGenerate aArgs
cChars = ""
if oLower.isSelected()
cChars += "abcdefghijklmnopqrstuvwxyz"
ok
if oUpper.isSelected()
cChars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
ok
if oDigits.isSelected()
cChars += "0123456789"
ok
if oSymbols.isSelected()
cChars += "!@#$%^&*()-_=+[]{};:,.?"
ok
if cChars = ""
oPassword.setText("choose some characters")
return
ok
cPassword = ""
for nI = 1 to oLength.getValue()
cPassword += cChars[1 + oRandom.@nextInt(len(cChars))]
next
oPassword.setText(cPassword)
func onCopy aArgs
oClipboard = jStatic("java.awt.Toolkit","getDefaultToolkit",[]).getSystemClipboard()
oClipboard.setContents(new StringSelection(oPassword.getText()),NULL)
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
aChecks + ["the length at the start",len(oPassword.getText()),16]
oLength.setValue(8)
onGenerate(NULL)
aChecks + ["a shorter password",len(oPassword.getText()),8]
oLower.setSelected(false)
oUpper.setSelected(false)
onGenerate(NULL)
cText = oPassword.getText()
nDigits = 0
for nI = 1 to len(cText)
if isdigit(cText[nI])
nDigits++
ok
next
aChecks + ["digits only",nDigits,8]
oDigits.setSelected(false)
onGenerate(NULL)
aChecks + ["nothing chosen",oPassword.getText(),"choose some characters"]
return aChecks
Pong
Pong: Up/Down (or W/S) move your paddle, the computer plays the other one. A Swing timer moves the ball.
cd samples/UsingJava/applications/Pong then ring Pong.ringSource code
# Pong: Up/Down (or W/S) move your paddle, the computer plays the other one. A Swing timer moves the ball.
load "java.ring"
using {
"javax.swing"
"java.awt.event"
}
C_WIDTH = 600
C_HEIGHT = 400
C_PADDLE_HEIGHT = 80
C_PADDLE_WIDTH = 12
nPlayerY = 160 # the top of the paddles
nComputerY = 160
nBallX = 300
nBallY = 200
nBallDX = 5
nBallDY = 3
nPlayerScore = 0
nComputerScore = 0
nPlayerMove = 0 # -1, 0 or 1 while a key is held
nUpHeld = 0 # 1 while Up or W is held
nDownHeld = 0
oCanvas = new JCanvas(C_WIDTH,C_HEIGHT)
oScore = new JLabel("")
oFrame = new JFrame("Pong")
oFrame.setDefaultCloseOperation(2)
oFrame.add([oScore,"North"])
oFrame.add([oCanvas.component(),"Center"])
oFrame.pack()
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
oCanvas.component().setFocusable(true)
oCanvas.component().addKeyListener("onKey")
oCanvas.component().requestFocus()
oTimer = jTimer(20,"onTick")
oTimer.start()
draw()
jAutoClose()
jMainLoop()
oTimer.stop()
func onKey aArgs
if cJavaMethod = "keyPressed"
keyChanged(aArgs[1].getKeyCode(),true)
but cJavaMethod = "keyReleased"
keyChanged(aArgs[1].getKeyCode(),false)
ok
func keyChanged nCode, lDown
nDirection = 0
if nCode = 38 or nCode = 87 # Up, W
nDirection = -1
but nCode = 40 or nCode = 83 # Down, S
nDirection = 1
else
return
ok
if nDirection = -1 # two keys can be held: releasing one must not stop the other
nUpHeld = lDown
else
nDownHeld = lDown
ok
nPlayerMove = nDownHeld - nUpHeld
func clampPaddle nY
if nY < 0
return 0
but nY > C_HEIGHT - C_PADDLE_HEIGHT
return C_HEIGHT - C_PADDLE_HEIGHT
ok
return nY
# the ball speeds up at every hit; a ball faster than the paddle is thick would pass through it
func limitSpeed
if fabs(nBallDX) > 14
nBallDX = 14 * nBallDX / fabs(nBallDX)
ok
if fabs(nBallDY) > 9
nBallDY = 9 * nBallDY / fabs(nBallDY)
ok
func serve nDirection
nBallX = C_WIDTH / 2
nBallY = C_HEIGHT / 2
nBallDX = 5 * nDirection
nBallDY = 3
func onTick aArgs
tick()
# one step of the game
func tick
nPlayerY = clampPaddle(nPlayerY + nPlayerMove * 7)
nTarget = nBallY - C_PADDLE_HEIGHT / 2 # the computer follows the ball slowly
if nComputerY < nTarget - 4
nComputerY = clampPaddle(nComputerY + 4)
but nComputerY > nTarget + 4
nComputerY = clampPaddle(nComputerY - 4)
ok
nBallX += nBallDX
nBallY += nBallDY
if nBallY < 6 or nBallY > C_HEIGHT - 6
nBallDY = -nBallDY
ok
if nBallDX < 0 and nBallX < 30 + C_PADDLE_WIDTH and nBallY >= nPlayerY and nBallY <= nPlayerY + C_PADDLE_HEIGHT
nBallDX = -nBallDX * 1.05
nBallDY += (nBallY - (nPlayerY + C_PADDLE_HEIGHT / 2)) / 12
limitSpeed()
ok
if nBallDX > 0 and nBallX > C_WIDTH - 30 - C_PADDLE_WIDTH and nBallY >= nComputerY and nBallY <= nComputerY + C_PADDLE_HEIGHT
nBallDX = -nBallDX * 1.05
nBallDY += (nBallY - (nComputerY + C_PADDLE_HEIGHT / 2)) / 12
limitSpeed()
ok
if nBallX < 0
nComputerScore++
serve(1)
but nBallX > C_WIDTH
nPlayerScore++
serve(-1)
ok
draw()
func draw
oCanvas.clear("black")
oCanvas.color("gray")
for nY = 0 to C_HEIGHT step 24
oCanvas.fillRect(C_WIDTH / 2 - 2,nY,4,12)
next
oCanvas.color(jColor(30,144,255))
oCanvas.fillRect(30,floor(nPlayerY),C_PADDLE_WIDTH,C_PADDLE_HEIGHT)
oCanvas.color(jColor(255,99,71))
oCanvas.fillRect(C_WIDTH - 30 - C_PADDLE_WIDTH,floor(nComputerY),C_PADDLE_WIDTH,C_PADDLE_HEIGHT)
oCanvas.color("white")
oCanvas.fillOval(floor(nBallX) - 7,floor(nBallY) - 7,14,14)
oScore.setText(" You " + nPlayerScore + " : " + nComputerScore + " Computer")
oCanvas.update()
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
oTimer.stop()
aChecks + ["paddle stays on top",clampPaddle(-20),0]
aChecks + ["paddle stays at the bottom",clampPaddle(500),C_HEIGHT - C_PADDLE_HEIGHT]
keyChanged(87,true)
aChecks + ["W moves up",nPlayerMove,-1]
keyChanged(87,false)
aChecks + ["the key up stops it",nPlayerMove,0]
keyChanged(40,true)
aChecks + ["Down moves down",nPlayerMove,1]
keyChanged(40,false)
nPlayerY = 100
nComputerY = 100
nBallX = 25
nBallY = 130
nBallDX = -5
nBallDY = 0
tick()
aChecks + ["the paddle returns the ball",nBallDX > 0,true]
nBallX = C_WIDTH - 2
nBallY = 10
nBallDX = 5
nBallDY = 0
nPlayerScore = 0
tick()
aChecks + ["a goal counts",nPlayerScore,1]
aChecks + ["the score text",trim(oScore.getText()),"You 1 : 0 Computer"]
keyChanged(38,true)
keyChanged(40,true)
keyChanged(38,false)
aChecks + ["releasing Up keeps Down",nPlayerMove,1]
keyChanged(40,false)
nBallDX = 80
nBallDY = -50
limitSpeed()
aChecks + ["the ball speed is limited",nBallDX * 100 + nBallDY,1391]
return aChecks
Rock Paper Scissors
Rock, paper, scissors against the computer.
cd samples/UsingJava/applications/RockPaperScissors then ring RockPaperScissors.ringSource code
# Rock, paper, scissors against the computer.
load "java.ring"
using {
"javax.swing"
"java.awt"
}
aNames = ["Rock","Paper","Scissors"]
nWins = 0
nLosses = 0
nTies = 0
oFrame = new JFrame("Rock, paper, scissors")
oFrame.setDefaultCloseOperation(2)
aButtons = []
oBar = new JPanel
oBar.add(new JLabel("Choose:"))
for nChoice = 1 to 3
oButton = new JButton(aNames[nChoice])
oButton.setActionCommand("" + nChoice)
oButton.addActionListener("onChoice")
aButtons + oButton
oBar.add(oButton)
next
oResult = new JLabel("Make your move")
oResult.setFont((new Font).@New(["SansSerif",1,16]))
oResult.setHorizontalAlignment(0)
oScore = new JLabel("")
oScore.setHorizontalAlignment(0)
oHistory = new DefaultListModel
oTop = new JPanel((new GridLayout).@New([3,1,4,4]))
oTop.add(oBar)
oTop.add(oResult)
oTop.add(oScore)
oFrame.add([oTop,"North"])
oFrame.add([new JScrollPane(new JList(oHistory)),"Center"])
oFrame.setSize([400,320])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
showScore()
jAutoClose()
jMainLoop()
# 1 = the player wins, 0 = tie, -1 = the computer wins (rock = 1, paper = 2, scissors = 3)
func compare nPlayer, nComputer
if nPlayer = nComputer
return 0
but (nPlayer = 1 and nComputer = 3) or (nPlayer = 2 and nComputer = 1) or (nPlayer = 3 and nComputer = 2)
return 1
ok
return -1
func showScore
oScore.setText("Wins " + nWins + " Losses " + nLosses + " Ties " + nTies)
func playAgainst nPlayer, nComputer
nOutcome = compare(nPlayer,nComputer)
switch nOutcome
on 1
nWins++
cText = "You win! " + aNames[nPlayer] + " beats " + aNames[nComputer]
on 0
nTies++
cText = "Tie: both chose " + aNames[nPlayer]
on -1
nLosses++
cText = "You lose. " + aNames[nComputer] + " beats " + aNames[nPlayer]
off
oResult.setText(cText)
oHistory.insertElementAt(cText,0)
showScore()
return nOutcome
func onChoice aArgs
playAgainst(0 + aArgs[1].getActionCommand(),random(2) + 1)
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
aChecks + ["rock beats scissors",compare(1,3),1]
aChecks + ["paper beats rock",compare(2,1),1]
aChecks + ["scissors lose to rock",compare(3,1),-1]
aChecks + ["a tie",compare(2,2),0]
playAgainst(1,3)
aChecks + ["a win",oResult.getText(),"You win! Rock beats Scissors"]
playAgainst(1,2)
aChecks + ["a loss",oResult.getText(),"You lose. Paper beats Rock"]
playAgainst(3,3)
aChecks + ["a tie text",oResult.getText(),"Tie: both chose Scissors"]
aChecks + ["the score",oScore.getText(),"Wins 1 Losses 1 Ties 1"]
aButtons[2].doClick()
aChecks + ["a button plays a round",nWins + nLosses + nTies,4]
aChecks + ["the history",oHistory.getSize(),4]
return aChecks
Sales Explorer
Explore a list of sales with jQuery: filter by region and product, sort, and see the totals by product. The window is made with the builders.
cd samples/UsingJava/applications/SalesExplorer then ring SalesExplorer.ringSource code
# Explore a list of sales with jQuery: filter by region and product, sort, and see the totals by product. The window is made with the builders.
load "java.ring"
using {
"javax.swing.table"
}
# [region, product, units, unit price]
aSales = []
aRegions = ["North","South","East","West"]
aProducts = ["Ring book","Ring course","Java bridge","Coffee"]
aPrices = [30,120,80,4]
for nAt = 1 to 40
nRegion = (nAt * 7) % 4 + 1
nProduct = (nAt * 5) % 4 + 1
aSales + [aRegions[nRegion],aProducts[nProduct],(nAt * 13) % 9 + 1,aPrices[nProduct]]
next
oWin = jWindow("Sales explorer",640,480)
oRegion = jCombo(["All regions","North","South","East","West"],"onRefresh")
oSearch = jField("",14,"onRefresh")
oSort = jCombo(["Product","Units","Revenue"],"onRefresh")
oModel = (new DefaultTableModel).@New([jArray("java.lang.String",["Region","Product","Units","Price","Revenue"]),0])
oTable = new JTable(oModel)
oTotals = jLabel(" ")
oByProduct = jLabel(" ")
oWin.add([jBorder(
jScroll(oTable),
jPad(jRow([jLabel("Region"),oRegion,jLabel("Product contains"),oSearch,jLabel("Sort by"),oSort],6),6),
jPad(jColumn([oTotals,oByProduct],4),6),
NULL,
NULL
),"Center"])
refresh()
jShow(oWin)
jAutoClose()
jMainLoop()
func refresh
oQuery = jQuery(aSales)
if oRegion.getSelectedIndex() > 0
cRegion = oRegion.getSelectedItem()
oQuery = oQuery.filter("x[1] = '" + cRegion + "'")
ok
cText = lower(trim(oSearch.getText()))
if cText != ""
oQuery = oQuery.filter("substr(lower(x[2]),'" + substr(cText,"'","' + char(39) + '") + "') > 0")
ok
cSort = oSort.getSelectedItem()
if cSort = "Product"
oQuery = oQuery.sortBy("x[2]").thenBy("x[1]")
but cSort = "Units"
oQuery = oQuery.sortByDesc("x[3]")
else
oQuery = oQuery.sortByDesc("x[3] * x[4]")
ok
aRows = oQuery.toList()
oModel.setRowCount(0)
for aRow in aRows
oModel.addRow(jArray("java.lang.Object",[aRow[1],aRow[2],aRow[3],aRow[4],aRow[3] * aRow[4]]))
next
nTotal = jQuery(aRows).sum("x[3] * x[4]")
oTotals.setText(" " + len(aRows) + " sales, " + jQuery(aRows).sum("x[3]") + " units, revenue " + nTotal)
aGroups = jQuery(aRows).groupBy("x[2]").map("x[1] + ': ' + jQuery(x[2]).sum('x[3] * x[4]')").toList()
oByProduct.setText(" " + jQuery(aGroups).join(" "))
func onRefresh aArgs
refresh()
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
aChecks + ["all the sales",oModel.getRowCount(),40]
oRegion.setSelectedIndex(1)
refresh()
aChecks + ["one region",oModel.getRowCount(),10]
oRegion.setSelectedIndex(0)
oSearch.setText("coffee")
refresh()
aChecks + ["a product",oModel.getRowCount(),10]
oRegion.setSelectedIndex(1)
refresh()
aChecks + ["a product in a region",oModel.getRowCount(),0]
oSearch.setText("o'brien")
refresh()
aChecks + ["a quote in the search is not an error",oModel.getRowCount(),0]
oSearch.setText("")
return aChecks
Snake Game
Snake: arrow keys steer, a timer moves the snake, the board is a picture that the timer draws again.
cd samples/UsingJava/applications/SnakeGame then ring SnakeGame.ringSource code
# Snake: arrow keys steer, a timer moves the snake, the board is a picture that the timer draws again.
load "java.ring"
using {
"javax.swing"
"java.awt"
"java.awt.image"
"java.awt.event"
}
nCells = 20
nSize = 16
aSnake = [[10,10],[9,10],[8,10]] # the head first
nDX = 0
nDY = 0 # the snake waits for the first arrow key
aFood = [15,10]
nScore = 0
lOver = false
oImage = (new BufferedImage).@New([nCells * nSize,nCells * nSize,1])
oLabel = new JLabel(new ImageIcon(oImage))
oLabel.setFocusable(true)
oStatus = new JLabel("Press an arrow key (R restarts)")
oFrame = new JFrame("Snake")
oFrame.setDefaultCloseOperation(2)
oFrame.add([oLabel,"Center"])
oFrame.add([oStatus,"South"])
oFrame.pack()
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
oLabel.addKeyListener("onKey")
oLabel.requestFocus()
oTimer = jTimer(120,"onTick")
oTimer.start()
draw()
jAutoClose()
jMainLoop()
oTimer.stop()
func onKey aArgs
if cJavaMethod != "keyPressed"
return
ok
nCode = aArgs[1].getKeyCode()
nHX = aSnake[1][1] # the head; the snake cannot turn back into its neck
nHY = aSnake[1][2]
nNX = aSnake[2][1]
nNY = aSnake[2][2]
if nCode = 37 and nNX != nHX - 1 # left, up, right, down
nDX = -1 nDY = 0
but nCode = 39 and nNX != nHX + 1
nDX = 1 nDY = 0
but nCode = 38 and nNY != nHY - 1
nDX = 0 nDY = -1
but nCode = 40 and nNY != nHY + 1
nDX = 0 nDY = 1
but nCode = 82
restart()
ok
func restart
aSnake = [[10,10],[9,10],[8,10]]
nDX = 0
nDY = 0
nScore = 0
lOver = false
placeFood()
draw()
oStatus.setText("Press an arrow key (R restarts)")
func placeFood
if len(aSnake) >= nCells * nCells # the snake fills the board: no free cell to look for
return
ok
while true
aFood = [random(nCells - 1),random(nCells - 1)]
lFree = true
for aPart in aSnake
if aPart[1] = aFood[1] and aPart[2] = aFood[2]
lFree = false
ok
next
if lFree
return
ok
end
func onTick aArgs
if lOver or (nDX = 0 and nDY = 0)
return
ok
nX = aSnake[1][1] + nDX
nY = aSnake[1][2] + nDY
if nX < 0 or nY < 0 or nX >= nCells or nY >= nCells
return gameOver()
ok
for aPart in aSnake
if aPart[1] = nX and aPart[2] = nY
return gameOver()
ok
next
insert(aSnake,0,[nX,nY])
if nX = aFood[1] and nY = aFood[2]
nScore++
oStatus.setText("Score: " + nScore)
placeFood()
else
del(aSnake,len(aSnake))
ok
draw()
func gameOver
lOver = true
oStatus.setText("Game over - score " + nScore + " (R restarts)")
func draw
g = oImage.createGraphics()
g.setColor(jColor(20,30,20))
g.fillRect(0,0,nCells * nSize,nCells * nSize)
g.setColor(jColor(220,60,60))
g.fillOval(aFood[1] * nSize + 1,aFood[2] * nSize + 1,nSize - 2,nSize - 2)
for nI = 1 to len(aSnake)
if nI = 1
g.setColor(jColor(140,240,120))
else
g.setColor(jColor(70,170,70))
ok
g.fillRect(aSnake[nI][1] * nSize + 1,aSnake[nI][2] * nSize + 1,nSize - 2,nSize - 2)
next
g.dispose()
oLabel.repaint()
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
aFood = [12,10]
nDX = 1
nDY = 0
onTick(NULL)
onTick(NULL)
aChecks + ["the snake eats",nScore,1]
aChecks + ["the snake grows",len(aSnake),4]
restart()
aChecks + ["restart",len(aSnake),3]
aSnake = [[19,10],[18,10],[17,10]]
nDX = 1
nDY = 0
onTick(NULL)
aChecks + ["the wall ends the game",left(oStatus.getText(),9),"Game over"]
aSnake = [[3,3],[2,3],[1,3]]
aFood = [9,9]
restart()
aChecks + ["restart draws the board again",oImage.getRGB([aFood[1] * nSize + 8,aFood[2] * nSize + 8]) != oImage.getRGB([0,0]),true]
return aChecks
Sokoban
Sokoban: push every box onto a target with the arrow keys. The squares are drawn on a JCanvas. # wall @ player $ box . target * box on a target + player on a target
cd samples/UsingJava/applications/Sokoban then ring Sokoban.ringSource code
# Sokoban: push every box onto a target with the arrow keys. The squares are drawn on a JCanvas.
# # wall @ player $ box . target * box on a target + player on a target
load "java.ring"
using {
"javax.swing"
"java.awt.event"
}
C_CELL = 34
aLevels = [
["#######",
"#.@ $ #",
"# #",
"#######"],
["########",
"# #",
"# .$.$ #",
"# @ #",
"########"],
[" #####",
"### #",
"#.@$ #",
"### $.#",
"#.##$ #",
"# # . ##",
"#$ *$$.#",
"# . #",
"########"]
]
nLevel = 1
aMap = [] # list of strings
nPlayerColumn = 0
nPlayerRow = 0
nMoves = 0
aImages = [] # [tile, picture] for every kind of square: loaded once
oCanvas = new JCanvas(8 * C_CELL,9 * C_CELL)
oInfo = new JLabel("")
oRestart = new JButton("Restart")
oNext = new JButton("Next")
oRestart.addActionListener("onRestart")
oNext.addActionListener("onNext")
oSouth = new JPanel(new BorderLayout)
oSouth.add([oInfo,"Center"])
oButtons = new JPanel
oButtons.add(oRestart)
oButtons.add(oNext)
oSouth.add([oButtons,"East"])
oFrame = new JFrame("Sokoban")
oFrame.setDefaultCloseOperation(2)
oFrame.add([oCanvas.component(),"Center"])
oFrame.add([oSouth,"South"])
oFrame.pack()
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
oCanvas.component().setFocusable(true)
oCanvas.component().addKeyListener("onKey")
oCanvas.component().requestFocus()
loadImages()
loadLevel(1)
jAutoClose()
jMainLoop()
func onRestart aArgs
loadLevel(nLevel)
oCanvas.component().requestFocus()
func onNext aArgs
nextLevel()
oCanvas.component().requestFocus()
func loadLevel nNumber
nLevel = nNumber
aMap = []
for cRow in aLevels[nLevel]
aMap + cRow
next
nMoves = 0
for nRow = 1 to len(aMap)
for nColumn = 1 to len(aMap[nRow])
if aMap[nRow][nColumn] = "@" or aMap[nRow][nColumn] = "+"
nPlayerColumn = nColumn
nPlayerRow = nRow
ok
next
next
draw()
func nextLevel
loadLevel(nLevel % len(aLevels) + 1)
func tileAt nColumn, nRow
if nRow < 1 or nRow > len(aMap) or nColumn < 1 or nColumn > len(aMap[nRow])
return "#"
ok
return aMap[nRow][nColumn]
func setTile nColumn, nRow, cTile
aMap[nRow][nColumn] = cTile
func isTarget cTile
return cTile = "." or cTile = "*" or cTile = "+"
func isBox cTile
return cTile = "$" or cTile = "*"
# the tile left behind: a target stays a target
func without cTile
if isTarget(cTile)
return "."
ok
return " "
func move nDx, nDy
nTargetColumn = nPlayerColumn + nDx
nTargetRow = nPlayerRow + nDy
cTarget = tileAt(nTargetColumn,nTargetRow)
if cTarget = "#"
return false
but isBox(cTarget)
cBeyond = tileAt(nTargetColumn + nDx,nTargetRow + nDy)
if cBeyond = "#" or isBox(cBeyond)
return false
ok
if isTarget(cBeyond) # push the box
setTile(nTargetColumn + nDx,nTargetRow + nDy,"*")
else
setTile(nTargetColumn + nDx,nTargetRow + nDy,"$")
ok
ok
cHere = tileAt(nPlayerColumn,nPlayerRow) # move the player
setTile(nPlayerColumn,nPlayerRow,without(cHere))
if isTarget(cTarget)
setTile(nTargetColumn,nTargetRow,"+")
else
setTile(nTargetColumn,nTargetRow,"@")
ok
nPlayerColumn = nTargetColumn
nPlayerRow = nTargetRow
nMoves++
return true
func boxesLeft
nCount = 0
for cRow in aMap
for x = 1 to len(cRow)
if cRow[x] = "$"
nCount++
ok
next
next
return nCount
func onKey aArgs
if cJavaMethod != "keyPressed"
return
ok
nCode = aArgs[1].getKeyCode()
if nCode = 37
move(-1,0)
but nCode = 39
move(1,0)
but nCode = 38
move(0,-1)
but nCode = 40
move(0,1)
ok
draw()
func square nColumn, nRow, cTile
oCanvas.drawImage(imageOf(cTile),(nColumn - 1) * C_CELL,(nRow - 1) * C_CELL,C_CELL,C_CELL)
# the pictures are in the folder images next to the program
func loadImages
cFolder = ""
if len(sysargv) > 1
cFolder = jFolderOf(sysargv[2])
ok
aImages = []
for aTile in [[" ","empty"],["#","wall"],["@","player"],["+","player"],[".","door"],["$","box"],["*","boxondoor"]]
aImages + [aTile[1],oCanvas.loadImage(cFolder + "images/" + aTile[2] + ".jpg")]
next
func imageOf cTile
return aImages[find(aImages,cTile,1)][2]
func draw
oCanvas.clear("#222222")
for nRow = 1 to len(aMap)
for nColumn = 1 to len(aMap[nRow])
square(nColumn,nRow,aMap[nRow][nColumn])
next
next
if boxesLeft() = 0
oInfo.setText(" Level " + nLevel + " solved in " + nMoves + " moves!")
else
oInfo.setText(" Level " + nLevel + " moves " + nMoves)
ok
oCanvas.update()
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
loadLevel(1)
aChecks + ["the player is found",nPlayerColumn * 10 + nPlayerRow,32]
aChecks + ["a wall stops the player",move(0,-1),false]
aChecks + ["a free square",move(1,0),true]
aChecks + ["pushing a box",move(1,0),true]
aChecks + ["the box moved",tileAt(6,2),"$"]
aChecks + ["a box against the wall stays",move(1,0),false]
loadLevel(1)
move(-1,0)
aChecks + ["the player stands on a target",tileAt(2,2),"+"]
move(1,0)
aChecks + ["the target stays after leaving",tileAt(2,2),"."]
loadLevel(2)
aChecks + ["level 2 has two boxes",boxesLeft(),2]
nextLevel()
aChecks + ["next level",nLevel,3]
nextLevel()
aChecks + ["the levels go round",nLevel,1]
loadLevel(1)
oRestart.doClick()
aChecks + ["restart",nMoves,0]
# solve level 1: walk round the box, then push it left onto the target
loadLevel(1)
move(0,1)
move(1,0)
move(1,0)
move(1,0)
move(0,-1)
move(-1,0)
move(-1,0)
move(-1,0)
draw()
aChecks + ["the box is on the target",tileAt(2,2),"*"]
aChecks + ["no box left",boxesLeft(),0]
aChecks + ["the message",left(trim(oInfo.getText()),17),"Level 1 solved in"]
return aChecks
Stopwatch
A stopwatch with laps: a Swing timer updates the time, System.nanoTime measures it.
cd samples/UsingJava/applications/Stopwatch then ring Stopwatch.ringSource code
# A stopwatch with laps: a Swing timer updates the time, System.nanoTime measures it.
load "java.ring"
using {
"javax.swing"
"java.awt"
}
lRunning = false
nStart = 0
nBefore = 0
oFrame = new JFrame("Stopwatch")
oFrame.setDefaultCloseOperation(2)
oTime = new JLabel("00:00.0")
oTime.setHorizontalAlignment(0)
oTime.setFont((new Font).@New(["Monospaced",1,44]))
oStartStop = new JButton("Start")
oLap = new JButton("Lap")
oReset = new JButton("Reset")
oStartStop.addActionListener("onStartStop")
oLap.addActionListener("onLap")
oReset.addActionListener("onReset")
oButtons = new JPanel
oButtons.add(oStartStop)
oButtons.add(oLap)
oButtons.add(oReset)
oLaps = new DefaultListModel
oList = new JList(oLaps)
oFrame.add([oTime,"North"])
oFrame.add([new JScrollPane(oList),"Center"])
oFrame.add([oButtons,"South"])
oFrame.setSize([320,340])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
oTimer = jTimer(100,"tick")
oTimer.start()
jAutoClose()
jMainLoop()
oTimer.stop()
func elapsed
nTotal = nBefore
if lRunning
nTotal += (System.nanoTime() - nStart) / 1000000000
ok
return nTotal
func format nSeconds
nTenths = floor(nSeconds * 10)
nMinutes = floor(nTenths / 600)
nWhole = floor((nTenths % 600) / 10)
cMinutes = "" + nMinutes
if nMinutes < 10
cMinutes = "0" + cMinutes
ok
cSeconds = "" + nWhole
if nWhole < 10
cSeconds = "0" + cSeconds
ok
return cMinutes + ":" + cSeconds + "." + (nTenths % 10)
func tick aArgs
oTime.setText(format(elapsed()))
func onStartStop aArgs
if lRunning
nBefore = elapsed()
lRunning = false
oStartStop.setText("Start")
else
nStart = System.nanoTime()
lRunning = true
oStartStop.setText("Stop")
ok
func onLap aArgs
if lRunning
oLaps.addElement("Lap " + (oLaps.size() + 1) + " " + format(elapsed()))
ok
func onReset aArgs
lRunning = false
nBefore = 0
oStartStop.setText("Start")
oLaps.clear()
oTime.setText("00:00.0")
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
oStartStop.doClick()
oLap.doClick()
aChecks + ["a lap",oLaps.getSize(),1]
oReset.doClick()
aChecks + ["Reset clears the time",oTime.getText(),"00:00.0"]
aChecks + ["Reset clears the laps",oLaps.getSize(),0]
return aChecks
Sudoku
Sudoku: type the digits, "Check" marks the mistakes, "Solve" uses backtracking.
cd samples/UsingJava/applications/Sudoku then ring Sudoku.ringSource code
# Sudoku: type the digits, "Check" marks the mistakes, "Solve" uses backtracking.
load "java.ring"
using {
"javax.swing"
"java.awt"
"java.awt.event"
}
cPuzzle = "530070000600195000098000060800060003400803001700020006060000280000419005000080079"
aGrid = list(81) # the digits, 0 = empty
aFixed = list(81) # 1 for the digits that belong to the puzzle
aBoxes = []
oFrame = new JFrame("Sudoku")
oFrame.setDefaultCloseOperation(2)
oBoard = new JPanel((new GridLayout).@New([9,9,2,2]))
oBoard.setBorder(jStatic("javax.swing.BorderFactory","createEmptyBorder",[8,8,8,8]))
for nCell = 1 to 81
oBox = new JTextField("")
oBox.setHorizontalAlignment(0)
oBox.setFont((new Font).@New(["SansSerif",1,20]))
oBox.addKeyListener(jCallback("typed(" + nCell + ")"))
aBoxes + oBox
oBoard.add(oBox)
next
oInfo = new JLabel("")
oButtons = new JPanel
for aButton in [["New","onNew"],["Check","onCheck"],["Solve","onSolve"],["Clear","onClear"]]
oButton = new JButton(aButton[1])
oButton.addActionListener(aButton[2])
oButtons.add(oButton)
next
oSouth = new JPanel(new BorderLayout)
oSouth.add([oInfo,"North"])
oSouth.add([oButtons,"Center"])
oFrame.add([oBoard,"Center"])
oFrame.add([oSouth,"South"])
oFrame.setSize([460,540])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
loadPuzzle(cPuzzle)
jAutoClose()
jMainLoop()
func onNew aArgs
loadPuzzle(cPuzzle)
func onCheck aArgs
checkBoard()
func onSolve aArgs
solveBoard()
func onClear aArgs
loadPuzzle(copy("0",81))
func loadPuzzle cDigits
for nCell = 1 to 81
aGrid[nCell] = number(cDigits[nCell])
aFixed[nCell] = (aGrid[nCell] > 0)
if aGrid[nCell] > 0
aBoxes[nCell].setText("" + aGrid[nCell])
else
aBoxes[nCell].setText("")
ok
aBoxes[nCell].setEditable(not aFixed[nCell])
aBoxes[nCell].setForeground(jColor(0,0,0))
if aFixed[nCell]
aBoxes[nCell].setBackground(jColor(220,220,220))
else
aBoxes[nCell].setBackground(jColor(255,255,255))
ok
next
oInfo.setText(" Fill the empty squares")
# a key was released in a box: keep one digit 1-9, or clear the box
func typed nCell
if aFixed[nCell]
return
ok
cText = aBoxes[nCell].getText()
if len(cText) > 1
cText = right(cText,1)
ok
if len(cText) = 1 and isdigit(cText) and cText != "0"
aGrid[nCell] = number(cText)
else
cText = ""
aGrid[nCell] = 0
ok
if aBoxes[nCell].getText() != cText
aBoxes[nCell].setText(cText)
ok
aBoxes[nCell].setForeground(jColor(0,0,0))
# can nDigit go in the cell without breaking a rule
func canPlace aCells, nCell, nDigit
nRow = floor((nCell - 1) / 9)
nColumn = (nCell - 1) % 9
for nOther = 0 to 8
if aCells[nRow * 9 + nOther + 1] = nDigit and nRow * 9 + nOther + 1 != nCell
return false
but aCells[nOther * 9 + nColumn + 1] = nDigit and nOther * 9 + nColumn + 1 != nCell
return false
ok
next
nBoxRow = floor(nRow / 3) * 3
nBoxColumn = floor(nColumn / 3) * 3
for nR = 0 to 2
for nC = 0 to 2
nIndex = (nBoxRow + nR) * 9 + nBoxColumn + nC + 1
if aCells[nIndex] = nDigit and nIndex != nCell
return false
ok
next
next
return true
# backtracking solver; fills aCells and returns true when the puzzle has a solution
func solve aCells
nEmpty = 0
for nCell = 1 to 81
if aCells[nCell] = 0
nEmpty = nCell
exit
ok
next
if nEmpty = 0
return true
ok
for nDigit = 1 to 9
if canPlace(aCells,nEmpty,nDigit)
aCells[nEmpty] = nDigit
if solve(aCells)
return true
ok
aCells[nEmpty] = 0
ok
next
return false
func solveBoard
aWork = aGrid
if solve(aWork)
for nCell = 1 to 81
aGrid[nCell] = aWork[nCell]
aBoxes[nCell].setText("" + aWork[nCell])
next
oInfo.setText(" Solved")
else
oInfo.setText(" This puzzle has no solution")
ok
# mark the digits that break a rule
func checkBoard
nWrong = 0
for nCell = 1 to 81
if aGrid[nCell] > 0 and not canPlace(aGrid,nCell,aGrid[nCell])
aBoxes[nCell].setForeground(jColor(255,0,0))
nWrong++
else
aBoxes[nCell].setForeground(jColor(0,0,0))
ok
next
nEmpty = 0
for nValue in aGrid
if nValue = 0
nEmpty++
ok
next
if nWrong > 0
oInfo.setText(" " + nWrong + " digits break the rules")
but nEmpty > 0
oInfo.setText(" So far so good, " + nEmpty + " squares left")
else
oInfo.setText(" Complete and correct!")
ok
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
aChecks + ["the puzzle is loaded",aBoxes[1].getText(),"5"]
aChecks + ["a fixed box cannot be edited",aBoxes[1].isEditable(),false]
aChecks + ["an empty box can",aBoxes[3].isEditable(),true]
aBoxes[3].setText("5") # a 5 again in the first row
typed(3)
aChecks + ["a typed digit is stored",aGrid[3],5]
checkBoard()
aChecks + ["a wrong digit is found",left(trim(oInfo.getText()),1),"2"]
aChecks + ["and shown in red",aBoxes[3].getForeground().getRed(),255]
aBoxes[3].setText("x")
typed(3)
aChecks + ["a letter is refused",aBoxes[3].getText(),""]
aChecks + ["and the digit is gone",aGrid[3],0]
solveBoard()
aChecks + ["solved: the first row",aBoxes[3].getText(),"4"]
checkBoard()
aChecks + ["the solution is correct",trim(oInfo.getText()),"Complete and correct!"]
loadPuzzle("123456780" + "000000009" + copy("0",63))
solveBoard()
aChecks + ["an impossible puzzle",trim(oInfo.getText()),"This puzzle has no solution"]
return aChecks
Temperature Converter
Temperature converter: type in any box and the other two follow.
cd samples/UsingJava/applications/TemperatureConverter then ring TemperatureConverter.ringSource code
# Temperature converter: type in any box and the other two follow.
load "java.ring"
using {
"javax.swing"
"java.awt"
}
lUpdating = false
aLast = ["","",""] # the text that each box had when it was last converted
oFrame = new JFrame("Temperature converter")
oFrame.setDefaultCloseOperation(2)
oCelsius = new JTextField("")
oFahrenheit = new JTextField("")
oKelvin = new JTextField("")
oForm = new JPanel((new GridLayout).@New([3,2,8,8]))
oForm.setBorder(jStatic("javax.swing.BorderFactory","createEmptyBorder",[14,14,14,14]))
oForm.add(new JLabel("Celsius"))
oForm.add(oCelsius)
oForm.add(new JLabel("Fahrenheit"))
oForm.add(oFahrenheit)
oForm.add(new JLabel("Kelvin"))
oForm.add(oKelvin)
oCelsius.addKeyListener(jCallback("fromCelsius()"))
oFahrenheit.addKeyListener(jCallback("fromFahrenheit()"))
oKelvin.addKeyListener(jCallback("fromKelvin()"))
oFrame.add([oForm,"Center"])
oFrame.setSize([340,190])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
oCelsius.setText("20")
fromCelsius()
jAutoClose()
jMainLoop()
func isValidNumber cText
cText = trim(cText)
if cText = "" or cText = "-" or cText = "."
return false
ok
cDigits = substr(substr(cText,"-",""),".","")
for x = 1 to len(cDigits)
if not isdigit(cDigits[x])
return false
ok
next
return true
# a number with at most two decimals: 68 not 68.00
func formatNumber nValue
cText = string(floor(nValue * 100 + 0.5) / 100)
if substr(cText,".")
while right(cText,1) = "0"
cText = left(cText,len(cText) - 1)
end
if right(cText,1) = "."
cText = left(cText,len(cText) - 1)
ok
ok
return cText
func show oBox, nBox, nValue
oBox.setText(formatNumber(nValue))
aLast[nBox] = oBox.getText()
# a key that does not change the text (Tab, Shift, the arrows) must not convert again: the other boxes are rounded and would overwrite what was typed
func changed nBox, cText
if aLast[nBox] = cText
return false
ok
aLast[nBox] = cText
return true
func fromCelsius
if not changed(1,oCelsius.getText()) or not isValidNumber(oCelsius.getText())
return
ok
nValue = number(oCelsius.getText())
show(oFahrenheit,2,nValue * 9 / 5 + 32)
show(oKelvin,3,nValue + 273.15)
func fromFahrenheit
if not changed(2,oFahrenheit.getText()) or not isValidNumber(oFahrenheit.getText())
return
ok
nValue = (number(oFahrenheit.getText()) - 32) * 5 / 9
show(oCelsius,1,nValue)
show(oKelvin,3,nValue + 273.15)
func fromKelvin
if not changed(3,oKelvin.getText()) or not isValidNumber(oKelvin.getText())
return
ok
nValue = number(oKelvin.getText()) - 273.15
show(oCelsius,1,nValue)
show(oFahrenheit,2,nValue * 9 / 5 + 32)
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
aChecks + ["20 C in F",oFahrenheit.getText(),"68"]
aChecks + ["20 C in K",oKelvin.getText(),"293.15"]
oFahrenheit.setText("212")
fromFahrenheit()
aChecks + ["212 F in C",oCelsius.getText(),"100"]
aChecks + ["212 F in K",oKelvin.getText(),"373.15"]
oKelvin.setText("0")
fromKelvin()
aChecks + ["0 K in C",oCelsius.getText(),"-273.15"]
oCelsius.setText("-")
fromCelsius()
aChecks + ["half a number changes nothing",oKelvin.getText(),"0"]
aChecks + ["valid number",isValidNumber("-12.5"),true]
aChecks + ["invalid number",isValidNumber("12a"),false]
return aChecks
Tetris
Tetris: Left/Right move, Up turns, Down drops one row, Space drops all the way, R restarts. A Swing timer lets the piece fall.
cd samples/UsingJava/applications/Tetris then ring Tetris.ringSource code
# Tetris: Left/Right move, Up turns, Down drops one row, Space drops all the way, R restarts. A Swing timer lets the piece fall.
load "java.ring"
using {
"javax.swing"
"java.awt"
"java.awt.event"
}
C_COLUMNS = 10
C_ROWS = 20
C_CELL = 24
# the 7 pieces: each is a list of [column, row] cells (turned around the first cell)
aPieces = [
[[0,0],[-1,0],[1,0],[2,0]], # I
[[0,0],[1,0],[0,1],[1,1]], # O
[[0,0],[-1,0],[1,0],[0,1]], # T
[[0,0],[-1,0],[1,0],[1,1]], # L
[[0,0],[-1,0],[1,0],[-1,1]], # J
[[0,0],[1,0],[-1,1],[0,1]], # S
[[0,0],[-1,0],[0,1],[1,1]] # Z
]
aColors = [[0,200,220],[240,200,0],[150,50,170],[250,150,0],[60,90,210],[60,200,60],[220,40,40]]
aBoard = list(C_COLUMNS * C_ROWS) # 0 = empty, otherwise the piece number
aCurrent = [] # the cells of the falling piece (offsets)
nPiece = 0
nPieceX = 0
nPieceY = 0
nScore = 0
nLines = 0
lGameOver = false
oCanvas = new JCanvas(C_COLUMNS * C_CELL,C_ROWS * C_CELL)
oInfo = new JLabel("")
oInfo.setPreferredSize((new Dimension).@New([130,100]))
oInfo.setVerticalAlignment(1)
oInfo.setBorder(jStatic("javax.swing.BorderFactory","createEmptyBorder",[12,12,0,0]))
oFrame = new JFrame("Tetris")
oFrame.setDefaultCloseOperation(2)
oFrame.add([oCanvas.component(),"Center"])
oFrame.add([oInfo,"East"])
oFrame.pack()
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
oCanvas.component().setFocusable(true)
oCanvas.component().addKeyListener("onKey")
oCanvas.component().requestFocus()
oTimer = jTimer(500,"onTick")
newGame()
jAutoClose()
jMainLoop()
oTimer.stop()
func cellOf nColumn, nRow
return nRow * C_COLUMNS + nColumn + 1
# does the piece fit at the position
func fits aCells, nX, nY
for aCell in aCells
nColumn = nX + aCell[1]
nRow = nY + aCell[2]
if nColumn < 0 or nColumn >= C_COLUMNS or nRow >= C_ROWS
return false
but nRow >= 0 and aBoard[cellOf(nColumn,nRow)] != 0
return false
ok
next
return true
func rotated aCells
aNew = []
for aCell in aCells
aNew + [-aCell[2],aCell[1]]
next
return aNew
func newPiece
nPiece = random(len(aPieces) - 1) + 1
aCurrent = aPieces[nPiece]
nPieceX = 4
nPieceY = 0
if not fits(aCurrent,nPieceX,nPieceY)
lGameOver = true
oTimer.stop()
ok
func newGame
aBoard = list(C_COLUMNS * C_ROWS)
nScore = 0
nLines = 0
lGameOver = false
newPiece()
draw()
oTimer.start()
# lock the piece into the board and clear the full rows
func lockPiece
for aCell in aCurrent
nColumn = nPieceX + aCell[1]
nRow = nPieceY + aCell[2]
if nRow >= 0
aBoard[cellOf(nColumn,nRow)] = nPiece
ok
next
nCleared = clearRows()
aPoints = [0,100,300,500,800]
nScore += aPoints[nCleared + 1]
nLines += nCleared
newPiece()
func clearRows
nCleared = 0
nRow = C_ROWS - 1
while nRow >= 0
lFull = true
for nColumn = 0 to C_COLUMNS - 1
if aBoard[cellOf(nColumn,nRow)] = 0
lFull = false
exit
ok
next
if lFull
for nMove = nRow to 1 step -1 # everything above moves one row down
for nColumn = 0 to C_COLUMNS - 1
aBoard[cellOf(nColumn,nMove)] = aBoard[cellOf(nColumn,nMove - 1)]
next
next
for nColumn = 0 to C_COLUMNS - 1
aBoard[cellOf(nColumn,0)] = 0
next
nCleared++
else
nRow--
ok
end
return nCleared
func tick
if lGameOver
return
but fits(aCurrent,nPieceX,nPieceY + 1)
nPieceY++
else
lockPiece()
ok
draw()
func onTick aArgs
tick()
func onKey aArgs
if cJavaMethod != "keyPressed"
return
ok
nCode = aArgs[1].getKeyCode()
if nCode = 82
return newGame()
ok
if lGameOver
return
ok
if nCode = 37
if fits(aCurrent,nPieceX - 1,nPieceY)
nPieceX--
ok
but nCode = 39
if fits(aCurrent,nPieceX + 1,nPieceY)
nPieceX++
ok
but nCode = 38
aTurned = rotated(aCurrent)
if fits(aTurned,nPieceX,nPieceY)
aCurrent = aTurned
ok
but nCode = 40
tick()
but nCode = 32
while fits(aCurrent,nPieceX,nPieceY + 1)
nPieceY++
end
lockPiece()
ok
draw()
func drawCell nColumn, nRow, nKind
oCanvas.color(jColor(aColors[nKind][1],aColors[nKind][2],aColors[nKind][3]))
oCanvas.fillRect(nColumn * C_CELL + 1,nRow * C_CELL + 1,C_CELL - 2,C_CELL - 2)
func draw
oCanvas.clear(jColor(16,24,32))
for nRow = 0 to C_ROWS - 1
for nColumn = 0 to C_COLUMNS - 1
nValue = aBoard[cellOf(nColumn,nRow)]
if nValue > 0
drawCell(nColumn,nRow,nValue)
ok
next
next
if not lGameOver
for aCell in aCurrent
drawCell(nPieceX + aCell[1],nPieceY + aCell[2],nPiece)
next
ok
cText = "<html>Score " + nScore + "<br>Lines " + nLines
if lGameOver
cText += "<br><br>GAME OVER<br>(R restarts)"
ok
oInfo.setText(cText + "</html>")
oCanvas.update()
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
oTimer.stop()
aBoard = list(C_COLUMNS * C_ROWS)
aChecks + ["a piece fits in the middle",fits(aPieces[2],4,5),true]
aChecks + ["next to the left wall",fits(aPieces[2],1,5),true]
aChecks + ["not out of the left wall",fits(aPieces[1],0,5),false]
aChecks + ["not through the floor",fits(aPieces[2],4,C_ROWS - 1),false]
aTurned = rotated([[0,0],[1,0]])
aChecks + ["a turned cell",aTurned[2][1] * 10 + aTurned[2][2],1]
for nColumn = 0 to C_COLUMNS - 1
aBoard[cellOf(nColumn,C_ROWS - 1)] = 1
aBoard[cellOf(nColumn,C_ROWS - 2)] = 2
next
aBoard[cellOf(0,C_ROWS - 2)] = 0
aBoard[cellOf(3,C_ROWS - 3)] = 3
aChecks + ["one row is full",clearRows(),1]
aChecks + ["the rows above fall",aBoard[cellOf(3,C_ROWS - 2)],3]
aChecks + ["the incomplete row stays",aBoard[cellOf(5,C_ROWS - 1)],2]
newGame()
oTimer.stop()
nY = nPieceY
tick()
aChecks + ["the piece falls",nPieceY,nY + 1]
aChecks + ["the info text",left(oInfo.getText(),19),"<html>Score 0<br>Li"]
return aChecks
Tic Tac Toe
Tic-tac-toe: two players, nine buttons. A Ring function is the listener of all the buttons.
cd samples/UsingJava/applications/TicTacToe then ring TicTacToe.ringSource code
# Tic-tac-toe: two players, nine buttons. A Ring function is the listener of all the buttons.
load "java.ring"
using {
"javax.swing"
"java.awt"
}
aBoard = list(9) # "" , "X" or "O"
cTurn = "X"
lOver = false
nMoves = 0
aButtons = []
oFrame = new JFrame("Tic-tac-toe")
oFrame.setDefaultCloseOperation(2)
oFrame.setLayout(new BorderLayout)
oGrid = new JPanel((new GridLayout).@New([3,3,4,4]))
for nI = 1 to 9
oButton = new JButton(" ")
oButton.setFont((new Font).@New(["SansSerif",1,40]))
oButton.setActionCommand("" + nI)
oButton.addActionListener("onPlay")
aButtons + oButton
oGrid.add(oButton)
next
oStatus = new JLabel("X plays")
oStatus.setHorizontalAlignment(0)
oNew = new JButton("New game")
oNew.addActionListener("onNew")
oFrame.add([oGrid,"Center"])
oSouth = new JPanel(new BorderLayout)
oSouth.add([oStatus,"Center"])
oSouth.add([oNew,"East"])
oFrame.add([oSouth,"South"])
oFrame.setSize([300,360])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
jAutoClose()
jMainLoop()
func onPlay aArgs
nCell = 0 + aArgs[1].getActionCommand()
if lOver or aBoard[nCell] != ""
return
ok
aBoard[nCell] = cTurn
aButtons[nCell].setText(cTurn)
if winner(cTurn)
oStatus.setText(cTurn + " wins!")
lOver = true
return
ok
nMoves++
if nMoves = 9
oStatus.setText("A draw")
lOver = true
return
ok
if cTurn = "X"
cTurn = "O"
else
cTurn = "X"
ok
oStatus.setText(cTurn + " plays")
func onNew aArgs
for nI = 1 to 9
aBoard[nI] = ""
aButtons[nI].setText(" ")
next
cTurn = "X"
lOver = false
nMoves = 0
oStatus.setText("X plays")
# the eight lines of three cells
func winner cPlayer
aLines = [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7]]
for aLine in aLines
if aBoard[aLine[1]] = cPlayer and aBoard[aLine[2]] = cPlayer and aBoard[aLine[3]] = cPlayer
return true
ok
next
return false
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
for n = 1 to 5
aButtons[n].doClick()
next
aChecks + ["after five moves",oStatus.getText(),"O plays"]
aButtons[6].doClick()
aButtons[7].doClick()
aChecks + ["X completes the line",oStatus.getText(),"X wins!"]
oNew.doClick()
aChecks + ["New game",oStatus.getText(),"X plays"]
return aChecks
Todo List
A to-do list kept in a database: JavaDatabase for the rows, the window builders for the screen.
cd samples/UsingJava/applications/TodoList then ring TodoList.ringSource code
# A to-do list kept in a database: JavaDatabase for the rows, the window builders for the screen.
load "java.ring"
jMaven("com.h2database:h2:2.2.224")
oDb = new JavaDatabase("jdbc:h2:mem:todo",[
["Tasks",[
["Id","int",1],
["Title","string",0,[["required",1]]],
["Done","int",0,[["default",0]]]
]]
])
oDb.insert("Tasks",[["Title","Write the tutorial"]])
oDb.insert("Tasks",[["Title","Try the web server"],["Done",1]])
oDb.insert("Tasks",[["Title","Publish the package"]])
aIds = []
oWin = jWindow("To-do",440,380)
oTitle = jField("",20,"onAdd")
oAdd = jButton("Add","onAdd")
oFilter = jCombo(["All","Open","Done"],"onRefresh")
oList = jListBox([])
oToggle = jButton("Done / open","onToggle")
oDelete = jButton("Delete","onDelete")
oStatus = jLabel(" ")
oWin.add([jBorder(
jScroll(oList),
jPad(jBorder(oTitle,NULL,NULL,jLabel("New task "),jRow([oAdd,oFilter],6)),8),
jPad(jBorder(oStatus,NULL,NULL,NULL,jRow([oToggle,oDelete],6)),8),
NULL,
NULL
),"Center"])
refresh()
jShow(oWin)
jAutoClose()
jMainLoop()
oDb.close()
func refresh
oModel = oList.getModel()
oModel.clear()
aIds = []
aCondition = []
if oFilter.getSelectedIndex() = 1
aCondition = ["Done","=",0]
but oFilter.getSelectedIndex() = 2
aCondition = ["Done","=",1]
ok
for aRow in oDb.query("Tasks",[["where",aCondition],["orderby",[["Id","asc"]]]])
cMark = "[ ] "
if jDbValue(aRow,"done") = 1
cMark = "[x] "
ok
oModel.addElement(cMark + jDbValue(aRow,"title"))
aIds + jDbValue(aRow,"id")
next
nOpen = oDb.countWhere("Tasks",["Done","=",0])
oStatus.setText(" " + nOpen + " open of " + oDb.count("Tasks"))
func onRefresh aArgs
refresh()
func onAdd aArgs
cTitle = trim(oTitle.getText())
if cTitle != ""
oDb.insert("Tasks",[["Title",cTitle]])
oTitle.setText("")
refresh()
ok
func selectedId
nAt = oList.getSelectedIndex()
if nAt < 0
return 0
ok
return aIds[nAt + 1]
func onToggle aArgs
nId = selectedId()
if nId > 0
nDone = jDbValue(oDb.byKey("Tasks",nId),"done")
oDb.update("Tasks",nId,[["Done",1 - nDone]])
refresh()
ok
func onDelete aArgs
nId = selectedId()
if nId > 0
oDb.remove("Tasks",nId)
refresh()
ok
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
aChecks + ["the tasks at the start",len(aIds),3]
oTitle.setText("Water the plants")
oAdd.doClick()
aChecks + ["Add",len(aIds),4]
oList.setSelectedIndex(0)
oToggle.doClick()
oFilter.setSelectedIndex(1)
aChecks + ["the filter of the open tasks",len(aIds),2]
oFilter.setSelectedIndex(0)
oList.setSelectedIndex(0)
oDelete.doClick()
aChecks + ["Delete",len(aIds),3]
return aChecks
Towers Of Hanoi
Towers of Hanoi: click a peg to pick its top disk, click another peg to drop it; or let the program solve it.
cd samples/UsingJava/applications/TowersOfHanoi then ring TowersOfHanoi.ringSource code
# Towers of Hanoi: click a peg to pick its top disk, click another peg to drop it; or let the program solve it.
load "java.ring"
using {
"javax.swing"
"java.awt"
}
nDisks = 4
aPegs = [[],[],[]] # each peg is a list of disk sizes, the bottom disk first
nHeld = 0 # the peg we picked from (0 = nothing in the hand)
nMoves = 0
aPlan = [] # the moves of the solver: [from,to]
nPlanned = 0
lSolving = false # true while the solver plays: clicks are ignored
oCanvas = new JCanvas(600,300)
oFrame = new JFrame("Towers of Hanoi")
oFrame.setDefaultCloseOperation(2)
oCount = new JSpinner((new SpinnerNumberModel).@New([4,1,8,1]))
oNew = new JButton("New")
oSolve = new JButton("Solve")
oNew.addActionListener("onNew")
oSolve.addActionListener("onSolve")
oInfo = new JLabel("")
oBar = new JPanel
oBar.add(new JLabel("Disks:"))
oBar.add(oCount)
oBar.add(oNew)
oBar.add(oSolve)
oBar.add(oInfo)
oFrame.add([oCanvas.component(),"Center"])
oFrame.add([oBar,"South"])
oFrame.pack()
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
oCanvas.onPress("onPress")
oSolver = jTimer(300,"onStep")
newGame()
jAutoClose()
jMainLoop()
oSolver.stop()
func onNew aArgs
newGame()
func onSolve aArgs
startSolver()
func onStep aArgs
solverStep()
func newGame
oSolver.stop()
lSolving = false
nDisks = floor(0 + oCount.getValue())
aPegs = [[],[],[]]
for nSize = nDisks to 1 step -1
aPegs[1] + nSize
next
nHeld = 0
nMoves = 0
draw()
func diskColor nSize
aColors = [[230,25,75],[245,130,49],[255,225,25],[60,180,75],[67,99,216],[145,30,180],[240,50,230],[128,128,0]]
return jColor(aColors[nSize][1],aColors[nSize][2],aColors[nSize][3])
func draw
oCanvas.clear("white")
for nPeg = 1 to 3
nX = 100 + (nPeg - 1) * 200
oCanvas.color(jColor(139,69,19))
oCanvas.fillRect(nX - 4,60,8,220)
if nPeg = nHeld
oCanvas.color(jColor(255,140,0))
else
oCanvas.color("gray")
ok
oCanvas.fillRect(nX - 60,282,120,8)
for nLevel = 1 to len(aPegs[nPeg])
nSize = aPegs[nPeg][nLevel]
nWidth = 20 + nSize * 14
oCanvas.color(diskColor(nSize))
oCanvas.fillRect(nX - floor(nWidth / 2),262 - (nLevel - 1) * 24,nWidth,20)
next
next
if isSolved()
oInfo.setText("Solved in " + nMoves + " moves (minimum " + (pow(2,nDisks) - 1) + ")")
else
oInfo.setText("Moves: " + nMoves)
ok
oCanvas.update()
func isSolved
return len(aPegs[3]) = nDisks
# can the top disk of nFrom go to nTo
func canMove nFrom, nTo
if nFrom = nTo or len(aPegs[nFrom]) = 0
return false
but len(aPegs[nTo]) = 0
return true
ok
return aPegs[nFrom][len(aPegs[nFrom])] < aPegs[nTo][len(aPegs[nTo])]
func moveDisk nFrom, nTo
if not canMove(nFrom,nTo)
return false
ok
aPegs[nTo] + aPegs[nFrom][len(aPegs[nFrom])]
del(aPegs[nFrom],len(aPegs[nFrom]))
nMoves++
return true
func onPress nMouseX, nMouseY
clicked(nMouseX)
func clicked nMouseX
if lSolving # a click would leave a disk in the hand while the solver moves the disks
return
ok
nPeg = floor(nMouseX / 200) + 1
if nPeg > 3
nPeg = 3
ok
if nHeld = 0
if len(aPegs[nPeg]) > 0
nHeld = nPeg
ok
else
moveDisk(nHeld,nPeg)
nHeld = 0
ok
draw()
# the recursive solution, collected as a list of moves
func solve nCount, nFrom, nTo, nVia
if nCount = 0
return
ok
solve(nCount - 1,nFrom,nVia,nTo)
aPlan + [nFrom,nTo]
solve(nCount - 1,nVia,nTo,nFrom)
func startSolver
newGame()
aPlan = []
solve(nDisks,1,3,2)
nPlanned = 0
lSolving = true
oSolver.start()
func solverStep
nPlanned++
if nPlanned > len(aPlan)
oSolver.stop()
lSolving = false
return
ok
moveDisk(aPlan[nPlanned][1],aPlan[nPlanned][2])
draw()
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
newGame()
aChecks + ["four disks on the first peg",len(aPegs[1]),4]
aChecks + ["a big disk cannot go on a small one",canMove(1,2),true]
clicked(100)
clicked(300)
aChecks + ["a click moves the top disk",len(aPegs[2]),1]
aChecks + ["and counts as a move",nMoves,1]
clicked(100)
clicked(300)
aChecks + ["a bigger disk is refused",len(aPegs[2]),1]
oCount.setValue(3)
oNew.doClick()
aChecks + ["the spinner sets the disks",nDisks,3]
aPlan = []
solve(nDisks,1,3,2)
aChecks + ["the plan has 7 moves",len(aPlan),7]
for aMove in aPlan
moveDisk(aMove[1],aMove[2])
next
aChecks + ["the plan solves it",isSolved(),true]
draw()
aChecks + ["the message",left(oInfo.getText(),9),"Solved in"]
# a click during the solver is ignored
newGame()
startSolver()
clicked(100)
aChecks + ["no disk in the hand while solving",nHeld,0]
newGame()
clicked(100)
aChecks + ["clicks work again after New",nHeld,1]
newGame()
return aChecks
Typing Quiz
Typing quiz: type the sentence; the quiz measures the speed and counts the mistakes.
cd samples/UsingJava/applications/TypingQuiz then ring TypingQuiz.ringSource code
# Typing quiz: type the sentence; the quiz measures the speed and counts the mistakes.
load "java.ring"
using {
"javax.swing"
"java.awt"
}
aSentences = [
"The quick brown fox jumps over the lazy dog",
"Ring is a practical language for building applications",
"Swing controls can be used from Ring programs",
"A journey of a thousand miles begins with a single step"
]
cTarget = ""
nStartTime = 0
lStarted = false
nBest = 0
oFrame = new JFrame("Typing quiz")
oFrame.setDefaultCloseOperation(2)
oSentence = new JLabel("")
oSentence.setFont((new Font).@New(["SansSerif",0,16]))
oInput = new JTextField("")
oInput.setFont((new Font).@New(["SansSerif",0,16]))
oInput.getDocument().addDocumentListener("onChange")
oResult = new JLabel("")
oResult.setFont((new Font).@New(["SansSerif",1,14]))
oNew = new JButton("New sentence")
oNew.addActionListener("onNew")
oBest = new JLabel("")
oBottom = new JPanel
oBottom.add(oNew)
oBottom.add(oBest)
oMiddle = new JPanel((new GridLayout).@New([3,1,6,6]))
oMiddle.setBorder(jStatic("javax.swing.BorderFactory","createEmptyBorder",[10,14,10,14]))
oMiddle.add(oSentence)
oMiddle.add(oInput)
oMiddle.add(oResult)
oFrame.add([oMiddle,"Center"])
oFrame.add([oBottom,"South"])
oFrame.setSize([640,230])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
newSentence()
jAutoClose()
jMainLoop()
func onNew aArgs
newSentence()
func newSentence
cTarget = aSentences[random(len(aSentences) - 1) + 1]
oSentence.setText(cTarget)
oInput.setText("")
oResult.setText("Start typing...")
oResult.setForeground(jColor(0,0,0))
lStarted = false
oInput.requestFocus()
# the number of typed characters that differ from the target (the part that is not typed yet does not count)
func mistakes cTyped
nWrong = 0
for x = 1 to len(cTarget)
if x <= len(cTyped) and cTyped[x] != cTarget[x]
nWrong++
ok
next
if len(cTyped) > len(cTarget)
nWrong += len(cTyped) - len(cTarget)
ok
return nWrong
# words per minute: five characters make a word
func wordsPerMinute nCharacters, nMilliseconds
if nMilliseconds <= 0
return 0
ok
return floor((nCharacters / 5) / (nMilliseconds / 60000))
func onChange aArgs
typed()
func typed
cTyped = oInput.getText()
if cTyped = "" or cTarget = ""
if cTyped = ""
lStarted = false # an empty box starts again: the clock runs from the next first key
ok
return
but not lStarted
nStartTime = java_now()
lStarted = true
ok
if cTyped = cTarget
nSpeed = wordsPerMinute(len(cTarget),java_now() - nStartTime)
oResult.setText("Done! " + nSpeed + " words per minute")
oResult.setForeground(jColor(0,100,0))
if nSpeed > nBest
nBest = nSpeed
oBest.setText("Best: " + nBest + " wpm")
ok
else
nWrong = mistakes(cTyped)
if nWrong = 0
oResult.setText("Good so far...")
oResult.setForeground(jColor(0,0,0))
else
oResult.setText("" + nWrong + " characters are different")
oResult.setForeground(jColor(178,34,34))
ok
ok
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
cTarget = "Ring"
lStarted = false
aChecks + ["no mistakes",mistakes("Rin"),0]
aChecks + ["one mistake",mistakes("Rxn"),1]
aChecks + ["extra characters count",mistakes("Ringxx"),2]
aChecks + ["speed: 50 characters in 12 seconds",wordsPerMinute(50,12000),50]
oInput.setText("Rx")
typed()
aChecks + ["the result shows the mistake",oResult.getText(),"1 characters are different"]
oInput.setText("Ri")
typed()
aChecks + ["good so far",oResult.getText(),"Good so far..."]
oInput.setText("Ring")
typed()
aChecks + ["done",left(oResult.getText(),5),"Done!"]
oNew.doClick()
aChecks + ["a new sentence",oResult.getText(),"Start typing..."]
return aChecks
Unit Converter
A unit converter: lengths, weights and temperatures. A combo box chooses the kind, two combos the units.
cd samples/UsingJava/applications/UnitConverter then ring UnitConverter.ringSource code
# A unit converter: lengths, weights and temperatures. A combo box chooses the kind, two combos the units.
load "java.ring"
using {
"javax.swing"
"java.awt"
"java.awt.event"
}
# [name, [unit, factor to the base unit]...]; temperatures are a special case
aKinds = [
["Length",[["meter",1],["kilometer",1000],["centimeter",0.01],["mile",1609.344],["foot",0.3048],["inch",0.0254]]],
["Weight",[["kilogram",1],["gram",0.001],["pound",0.45359237],["ounce",0.028349523]]],
["Temperature",[["Celsius",1],["Fahrenheit",1],["Kelvin",1]]]
]
oFrame = new JFrame("Unit converter")
oFrame.setDefaultCloseOperation(2)
oFrame.setLayout(new GridLayout)
oPanel = new JPanel((new GridLayout).@New([5,2,8,8]))
oPanel.setBorder(jStatic("javax.swing.BorderFactory","createEmptyBorder",[12,12,12,12]))
oKind = new JComboBox
for aKind in aKinds
oKind.addItem(aKind[1])
next
oFrom = new JComboBox
oTo = new JComboBox
oValue = new JTextField("1")
oResult = new JLabel("")
oResult.setFont((new Font).@New(["SansSerif",1,16]))
oPanel.add(new JLabel("Kind"))
oPanel.add(oKind)
oPanel.add(new JLabel("From"))
oPanel.add(oFrom)
oPanel.add(new JLabel("To"))
oPanel.add(oTo)
oPanel.add(new JLabel("Value"))
oPanel.add(oValue)
oPanel.add(new JLabel("Result"))
oPanel.add(oResult)
oFrame.add(oPanel)
oFrame.setSize([360,260])
oFrame.setLocationRelativeTo(NULL)
oKind.addActionListener("onKind")
oFrom.addActionListener("onConvert")
oTo.addActionListener("onConvert")
oValue.addActionListener("onConvert")
oValue.getDocument().addDocumentListener("onConvert")
oFrame.setVisible(true)
onKind(NULL)
jAutoClose()
jMainLoop()
func onKind aArgs
nKind = oKind.getSelectedIndex() + 1
oFrom.removeAllItems()
oTo.removeAllItems()
for aUnit in aKinds[nKind][2]
oFrom.addItem(aUnit[1])
oTo.addItem(aUnit[1])
next
oTo.setSelectedIndex(1)
onConvert(NULL)
func onConvert aArgs
nKind = oKind.getSelectedIndex() + 1
nFrom = oFrom.getSelectedIndex() + 1
nTo = oTo.getSelectedIndex() + 1
if nFrom < 1 or nTo < 1
return
ok
cText = trim(oValue.getText())
if not isNumeric(cText)
oResult.setText("-")
return
ok
nValue = 0 + cText
if nKind = 3
nResult = convertTemperature(nValue,nFrom,nTo)
else
aUnits = aKinds[nKind][2]
nResult = nValue * aUnits[nFrom][2] / aUnits[nTo][2]
ok
oResult.setText(nice(floor(nResult * 10000 + 0.5) / 10000))
# a number as text with up to four decimals and no zeros at the end
func nice nNumber
decimals(4)
cText = "" + nNumber
if substr(cText,".")
while right(cText,1) = "0"
cText = left(cText,len(cText) - 1)
end
if right(cText,1) = "."
cText = left(cText,len(cText) - 1)
ok
ok
return cText
# a number as text: an optional minus, digits and at most one point
func isNumeric cText
nPoints = 0
if cText = ""
return false
ok
for nI = 1 to len(cText)
cChar = cText[nI]
if cChar = "."
nPoints++
but not (isdigit(cChar) or (cChar = "-" and nI = 1 and len(cText) > 1))
return false
ok
next
return nPoints <= 1 and cText != "." and cText != "-"
# 1 = Celsius, 2 = Fahrenheit, 3 = Kelvin: through Celsius
func convertTemperature nValue,nFrom,nTo
nCelsius = nValue
if nFrom = 2
nCelsius = (nValue - 32) * 5 / 9
but nFrom = 3
nCelsius = nValue - 273.15
ok
if nTo = 2
return nCelsius * 9 / 5 + 32
but nTo = 3
return nCelsius + 273.15
ok
return nCelsius
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
oValue.setText("100")
aChecks + ["100 metres in kilometres",oResult.getText(),"0.1"]
oValue.setText("x")
aChecks + ["not a number",oResult.getText(),"-"]
oKind.setSelectedIndex(2)
oValue.setText("100")
oTo.setSelectedIndex(1)
aChecks + ["100 degrees Celsius in Fahrenheit",oResult.getText(),"212"]
return aChecksWeb Api
A small web application: a to-do list with a web page and a JSON API, on JavaWebServer. ring WebApi.ring then open http://localhost:5080/ GET /api/todos POST /api/todos (the text is the body) DELETE /api/todos?id=1 ring WebApi.ring --selftest starts the server on a free port and calls it with jHttpGet and the others
cd samples/UsingJava/applications/WebApi then ring WebApi.ringSource code
# A small web application: a to-do list with a web page and a JSON API, on JavaWebServer.
# ring WebApi.ring then open http://localhost:5080/
# GET /api/todos POST /api/todos (the text is the body) DELETE /api/todos?id=1
# ring WebApi.ring --selftest starts the server on a free port and calls it with jHttpGet and the others
load "java.ring"
aTodos = [] # [id, text]
nNextId = 1
cAddress = "http://localhost:5080"
if jvSelfTestAsked()
cAddress = "http://127.0.0.1:0"
ok
oServer = new JavaWebServer(cAddress)
oServer.onGet("/","page")
oServer.onGet("/api/todos","listTodos")
oServer.onPost("/api/todos","addTodo")
oServer.onDelete("/api/todos","deleteTodo")
cUrl = oServer.url()
jAutoClose() # with --selftest: runs selfTest() and ends the program
? "Serving " + cUrl + " (Ctrl+C to stop)"
oServer.run()
# ---------------------------------------------------------------- handlers
func page oRequest
cHtml = "<html><body><h1>To-do list</h1><ul>"
for aTodo in aTodos
cHtml += "<li>" + aTodo[2] + " <a href='/api/todos?id=" + aTodo[1] + "'>(json)</a></li>"
next
cHtml += "</ul><p>POST /api/todos adds one, DELETE /api/todos?id=N removes one.</p></body></html>"
return cHtml
func listTodos oRequest
aList = []
for aTodo in aTodos
aList + [["id",aTodo[1]],["text",aTodo[2]]]
next
return jWebJson(aList)
func addTodo oRequest
cText = trim(oRequest.body())
if cText = ""
return [400,"text/plain","The text of the to-do is empty"]
ok
aTodos + [nNextId,cText]
nNextId++
return [201,"text/plain","added " + (nNextId - 1)]
func deleteTodo oRequest
nId = number(oRequest.query("id"))
for nIndex = 1 to len(aTodos)
if aTodos[nIndex][1] = nId
del(aTodos,nIndex)
return [200,"text/plain","deleted " + nId]
ok
next
return [404,"text/plain","There is no to-do " + nId]
# ---------------------------------------------------------------- self test: the program is its own client
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
aResult = jHttpGet(cUrl + "/api/todos")
aChecks + ["empty list",aResult[2],"[]"]
aResult = jHttpPost(cUrl + "/api/todos","write Ring code","text/plain")
aChecks + ["created",aResult[1],201]
jHttpPost(cUrl + "/api/todos","call Java","text/plain")
aResult = jHttpPost(cUrl + "/api/todos"," ","text/plain")
aChecks + ["empty text is a 400",aResult[1],400]
aResult = jHttpGet(cUrl + "/api/todos")
aChecks + ["the JSON list",aResult[2],'[{"id":1,"text":"write Ring code"},{"id":2,"text":"call Java"}]']
aResult = jHttpSend("DELETE",cUrl + "/api/todos?id=1","","")
aChecks + ["deleted",aResult[2],"deleted 1"]
aResult = jHttpSend("DELETE",cUrl + "/api/todos?id=9","","")
aChecks + ["missing is a 404",aResult[1],404]
aResult = jHttpGet(cUrl + "/")
aChecks + ["the web page lists the to-do",substr(aResult[2],"call Java") > 0,true]
oServer.close()
return aChecks
Web Dashboard
A small web server with a window: start and stop it, and watch the requests. The handlers are Ring functions; the window shows what they did.
cd samples/UsingJava/applications/WebDashboard then ring WebDashboard.ringSource code
# A small web server with a window: start and stop it, and watch the requests. The handlers are Ring functions; the window shows what they did.
load "java.ring"
oWin = jWindow("Web dashboard",520,380)
oServer = NULL
cBase = ""
nHits = 0
oStart = jButton("Start","onStart")
oStop = jButton("Stop","onStop")
oStop.setEnabled(false)
oAddress = jLabel("not running")
oCount = jLabel("0 requests")
oLog = jTextArea("",12,40)
oLog.setEditable(false)
oWin.add([jBorder(
jScroll(oLog),
jPad(jRow([oStart,oStop,oAddress],8),6),
jPad(oCount,6),
NULL,
NULL
),"Center"])
jShow(oWin)
jAutoClose()
jMainLoop()
if not isnull(oServer)
oServer.close()
ok
func onStart aArgs
if isobject(oServer)
return
ok
oServer = new JavaWebServer(0)
oServer.onGet("/","pageHome")
oServer.onGet("/time","pageTime")
oServer.onGet("/hello/:name","pageHello")
cBase = oServer.url()
oAddress.setText(cBase)
oStart.setEnabled(false)
oStop.setEnabled(true)
say("server started at " + cBase)
func onStop aArgs
if isobject(oServer)
oServer.close()
oServer = NULL
ok
oAddress.setText("not running")
oStart.setEnabled(true)
oStop.setEnabled(false)
say("server stopped")
func say cText
oLog.append(cText + nl)
oCount.setText("" + nHits + " requests")
func pageHome oRequest
nHits++
say("GET /")
return "<h1>Web dashboard</h1><p>Try /time and /hello/Ring</p>"
func pageTime oRequest
nHits++
say("GET /time")
return jWebJson([["time",date() + " " + time()]])
func pageHello oRequest
nHits++
say("GET " + oRequest.path())
return "Hello " + oRequest.param("name")
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
oStart.doClick()
aChecks + ["the address",left(cBase,7),"http://"]
aChecks + ["a request",jHttpGet(cBase + "/hello/Ann")[2],"Hello Ann"]
aChecks + ["the hits",nHits,1]
oStop.doClick()
aChecks + ["stopped",oAddress.getText(),"not running"]
return aChecks
Word Counter
Word counter: type or paste text, the statistics and the most frequent words update while you type.
cd samples/UsingJava/applications/WordCounter then ring WordCounter.ringSource code
# Word counter: type or paste text, the statistics and the most frequent words update while you type.
load "java.ring"
using {
"javax.swing"
"javax.swing.event"
"java.awt"
}
oFrame = new JFrame("Word counter")
oFrame.setDefaultCloseOperation(2)
oText = new JTextArea("Ring is a simple language. Java is a big platform. Ring can use the Java platform, and the Java platform can run Ring.")
oText.setLineWrap(true)
oText.setWrapStyleWord(true)
oStats = new JLabel(" ")
oTop = (new JTextArea).@New([8,20])
oTop.setEditable(false)
oTop.setFont((new Font).@New(["Monospaced",0,13]))
oSplit = (new JSplitPane).@New([0,new JScrollPane(oText),new JScrollPane(oTop)])
oSplit.setDividerLocation(130)
oFrame.add([oSplit,"Center"])
oFrame.add([oStats,"South"])
oFrame.setSize([460,380])
oFrame.setLocationRelativeTo(NULL)
oFrame.setVisible(true)
oText.getDocument().addDocumentListener("onChange")
update()
jAutoClose()
jMainLoop()
func onChange aArgs
update()
func update
cText = oText.getText()
aWords = words(cText)
aCount = [] # [word, count] pairs, as a list with a lookup table
aIndex = []
for cWord in aWords
nPos = find(aIndex,cWord)
if nPos = 0
aIndex + cWord
aCount + [cWord,1]
else
aCount[nPos][2]++
ok
next
aCount = sort(aCount,2) # by count, the biggest last
oStats.setText(" " + len(aWords) + " words, " + len(aIndex) + " different, " + oText.getDocument().getLength() + " characters")
cTop = ""
for nI = len(aCount) to Math.max(1,len(aCount) - 9) step -1
cTop += aCount[nI][1] + " : " + aCount[nI][2] + nl
next
oTop.setText(cTop)
func words cText
aList = []
cWord = ""
cText = lower(cText) + " "
for nI = 1 to len(cText)
cChar = cText[nI]
if isalpha(cChar) or cChar = "'" or ascii(cChar) > 127 # the bytes of a UTF-8 letter (Arabic, accents) are above 127
cWord += cChar
else
if cWord != ""
aList + cWord
cWord = ""
ok
ok
next
return aList
# the checks of --selftest: a list of [name, actual, expected]
func selfTest
aChecks = []
oText.setText("a b a")
aChecks + ["the statistics",oStats.getText()," 3 words, 2 different, 5 characters"]
aArabic = char(216) + char(167) + char(216) + char(168) + " " + char(216) + char(167)
aChecks + ["letters that are not ASCII stay in a word",len(words(aArabic)),2]
return aChecksSwing samples#
Small programs in samples/UsingJava/gui, one idea each: a form, a table, a tree, a calculator, the window builders and a canvas. See Swing samples.

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()Windows of the tutorials#
|  |  |
| A first window | Controls |
|  |  |
| Layouts | Menus and dialogs |
|  |  |
| Drawing and images | Animation |
|  | |
| Window builders |
JavaFX#
JavaFX is the other toolkit of Java, and it works from Ring too. The first run downloads the JavaFX jars (about 10 MB). See JavaFX.

Javafx hello
JavaFX: jJavaFX downloads the jars of this platform (about 10 MB, the first time), starts the toolkit and puts the program in GUI mode
ring samples/UsingJava/ecosystem/05_javafx_hello.ringSource code
# JavaFX: jJavaFX downloads the jars of this platform (about 10 MB, the first time), starts the toolkit and puts the program in GUI mode
load "java.ring"
jJavaFX("21.0.2")
jJavaFXClasses("21.0.2")
using {
"javafx.stage"
"javafx.scene"
"javafx.scene.control"
"javafx.scene.layout"
"javafx.geometry"
}
nClicks = 0
oLabel = new Label("Press the button")
oButton = new Button("Click me")
oButton.setOnAction("onClick")
oBox = (new VBox).@New([10])
oBox.setAlignment(jGetStatic("javafx.geometry.Pos","CENTER"))
oBox.getChildren().addAll([oLabel,oButton])
oStage = new Stage
oStage.setTitle("JavaFX from Ring")
oStage.setScene((new Scene).@New([oBox,320,160]))
oStage.show()
jAutoClose()
jMainLoop()
? "clicks: " + nClicks
func onClick aArgs
nClicks++
oLabel.setText("Clicked " + nClicks + " time(s)")