RingJavafor Ring

Menus and dialogs

A menu bar, a message box, a question and an input box.

What you will learn#

The program#

samples/UsingJava/tutorials/ch19_menus_dialogs.ring
# Tutorial 19: menus and dialogs - a menu bar, a message box, a question and an input box
load "java.ring"

using {
	"javax.swing"
	"java.awt"
	"java.awt.event"
}

oFrame = new JFrame("Notes")
oFrame.setDefaultCloseOperation(2)
oFrame.setSize([420,260])
oFrame.setLocationRelativeTo(NULL)
oArea = new JTextArea
oStatus = new JLabel(" Ready")
oFrame.add([new JScrollPane(oArea),"Center"])
oFrame.add([oStatus,"South"])

# a menu bar: JMenuBar > JMenu > JMenuItem
oBar = new JMenuBar
oFile = new JMenu("File")
oEdit = new JMenu("Edit")
addItem(oFile,"New","onNew")
addItem(oFile,"Exit","onExit")
addItem(oEdit,"Insert the date","onDate")
addItem(oEdit,"Count the words","onCount")
oBar.add(oFile)
oBar.add(oEdit)
oFrame.setJMenuBar(oBar)

oFrame.setVisible(true)
oArea.setText("A menu runs a Ring function.")

# the dialogs are modal: the Ring program waits in them, and its timers and events still run. The samples close them by themselves
if sysget("RINGJAVA_AUTOCLOSE") != ""
	oTimer = jTimer(800,"closeDialogs")
	oTimer.start()
ok
jAutoClose()
jMainLoop()

func addItem oMenu,cText,cFunction
	oItem = new JMenuItem(cText)
	oItem.addActionListener(cFunction)
	oMenu.add(oItem)

func onNew aArgs
	nAnswer = JOptionPane_confirm("Throw away the text?")
	if nAnswer = 0                             # 0 = YES
		oArea.setText("")
		oStatus.setText(" New document")
	ok

func onDate aArgs
	oArea.append(jStatic("java.time.LocalDate","now",[]).toString() + nl)

func onCount aArgs
	nWords = len(str2list(substr(trim(substr(oArea.getText()," ",nl)),"  ",nl)))
	jMessage("Words","The text has " + nWords + " words")

func onExit aArgs
	oFrame.dispose()

func JOptionPane_confirm cQuestion
	return jStatic("javax.swing.JOptionPane","showConfirmDialog",[oFrame,cQuestion,"Notes",0])

func closeDialogs aArgs
	aWindows = jStatic("java.awt.Window","getWindows",[]).toList()
	for oWindow in aWindows
		if jInstanceOf(oWindow,"javax.swing.JDialog")
			oWindow.dispose()
		ok
	next
A window with a menu bar
ch19_menus_dialogs.ring

How it works#

A dialog is modal: the Ring program waits inside it, and its timers and events keep running. The program closes its own dialogs after a moment so that it can run without a person; a real program does not need that.

Exercises#

  1. Ask for confirmation before the Exit item closes the window.
  2. Add a shortcut key to an item.
  3. Show the answer of an input box in a label.

Next#

Drawing and images

RingJava - use Java classes and methods from Ring programs.