RingJavafor Ring

A first window

A JFrame with a label, a text field and a button: layout and events.

What you will learn#

The program#

samples/UsingJava/tutorials/ch16_window.ring
# 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("")
The window of the first program
ch16_window.ring
After a name and a click
ch16_window.ring: greeted

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#

  1. Make the Enter key in the field do the same as the button.
  2. Show the number of greetings in the title.
  3. Add a Clear button.

Next#

Controls

RingJava - use Java classes and methods from Ring programs.