Controls
Check boxes, radio buttons, a combo box, a slider, a spinner, a list and a progress bar.
What you will learn#
- the common Swing controls,
- one function for several kinds of events,
- reading the state of a control.
The program#
# Tutorial 17: controls - check boxes, radio buttons, a combo box, a slider, a spinner, a list and a progress bar
load "java.ring"
using {
"javax.swing"
"java.awt"
"javax.swing.event"
}
oFrame = new JFrame("Controls")
oFrame.setDefaultCloseOperation(2)
oFrame.setLayout(new GridLayout)
oFrame.setSize([460,340])
oFrame.setLocationRelativeTo(NULL)
# a vertical box of rows
oBox = new JPanel
oBox.setLayout((new BoxLayout).@New([oBox,1])) # 1 = Y_AXIS
oBox.setBorder(BorderFactory_empty(12))
oCheck = new JCheckBox("Receive the news")
oRadio1 = new JRadioButton("Small")
oRadio2 = new JRadioButton("Large")
oRadio1.setSelected(true)
oGroup = new ButtonGroup # a group lets one radio button be selected at a time
oGroup.add(oRadio1)
oGroup.add(oRadio2)
oCombo = new JComboBox(["Ring","Java","C"])
oSlider = (new JSlider).@New([0,100])
oSlider.setValue(25)
oSpinner = new JSpinner((new SpinnerNumberModel).@New([5,0,10,1]))
oBar = (new JProgressBar).@New([0,100])
oBar.setValue(25)
oBar.setStringPainted(true)
oList = new JList(["red","green","blue"])
oInfo = new JLabel(" ")
for oItem in [oCheck,oRadio1,oRadio2,oCombo,oSlider,oSpinner,oBar,oList,oInfo]
oBox.add(oItem)
next
oFrame.add(oBox)
# a Ring function for each kind of event
oCheck.addActionListener("onChange")
oRadio1.addActionListener("onChange")
oRadio2.addActionListener("onChange")
oCombo.addActionListener("onChange")
oSlider.addChangeListener("onSlider") # a ChangeListener has one method, so a text is enough
oSpinner.addChangeListener("onChange")
oList.addListSelectionListener("onChange")
oFrame.setVisible(true)
onChange(NULL)
jAutoClose()
jMainLoop()
func onSlider aArgs
oBar.setValue(oSlider.getValue())
onChange(NULL)
func onChange aArgs
cSize = "Small"
if oRadio2.isSelected()
cSize = "Large"
ok
cList = oList.getSelectedValue()
if jIsNull(cList)
cList = "-"
ok
oInfo.setText("news=" + oCheck.isSelected() + " size=" + cSize + " " + oCombo.getSelectedItem() + " slider=" + oSlider.getValue() + " spin=" + oSpinner.getValue())
func BorderFactory_empty nSize
return jStatic("javax.swing.BorderFactory","createEmptyBorder",[nSize,nSize,nSize,nSize])
How it works#
Each control has a set... and a get.../is... method for its state and a listener for its change (addChangeListener, addActionListener, addItemListener). cJavaMethod tells which listener method was called when one function serves a listener with several.
Exercises#
- Show the value of the slider in a label.
- Disable a button until a check box is checked.
- Fill the combo box from a Ring list.