A first window
A JFrame with a label, a text field and a button: layout and events.
What you will learn#
using { "javax.swing" }, which switches the program to GUI mode,JFrame,BorderLayout,JPanel,- events: the name of a Ring function is a listener,
jMainLoop().
The program#
# Tutorial 16: a first window - JFrame, layout, a label, a text field, buttons and events
load "java.ring"
using {
"javax.swing"
"java.awt"
"java.awt.event"
}
# using { "javax.swing" } has switched the program to GUI mode: the calls of Ring run on the event thread of Swing,
# and the events (the Ring functions below) run on the Ring thread, in jMainLoop()
nCount = 0
oFrame = new JFrame("Greeter")
oFrame.setDefaultCloseOperation(2) # 2 = DISPOSE_ON_CLOSE: jMainLoop() ends when the window is closed
oFrame.setSize([380,170])
oFrame.setLocationRelativeTo(NULL)
# a window has a BorderLayout: North, South, East, West and Center
oTitle = new JLabel("What is your name?")
oTitle.setHorizontalAlignment(0)
oTitle.setFont((new Font).@New(["SansSerif",1,16]))
oFrame.add([oTitle,"North"])
# a panel with a FlowLayout holds the field and the button
oPanel = new JPanel
oField = new JTextField(14)
oButton = new JButton("Greet")
oPanel.add(oField)
oPanel.add(oButton)
oFrame.add([oPanel,"Center"])
oAnswer = new JLabel(" ")
oAnswer.setHorizontalAlignment(0)
oFrame.add([oAnswer,"South"])
# events: a Ring function name is a listener. The function gets the Java event in aArgs[1]
oButton.addActionListener("onGreet")
oField.addActionListener("onGreet") # Enter in the field does the same
oFrame.setVisible(true)
oField.requestFocus()
jAutoClose() # the samples close by themselves when RINGJAVA_AUTOCLOSE is set
jMainLoop()
? "greetings: " + nCount
func onGreet aArgs
cName = trim(oField.getText())
if cName = ""
oAnswer.setText("Please type a name")
return
ok
nCount++
oAnswer.setText("Hello, " + cName + "! (" + nCount + ")")
oField.setText("")

How it works#
using { "javax.swing" } makes the classes available and prepares the GUI: Swing calls run on the event thread, and the events (Ring functions) run on the Ring thread inside jMainLoop(), which ends when the last window closes. A function that is the listener gets the Java event in aArgs[1].
Exercises#
- Make the Enter key in the field do the same as the button.
- Show the number of greetings in the title.
- Add a Clear button.