Tutorial 11 - Intermediate Swing
This tutorial explores some of the many useful and interesting Java Swing components and widgets. Restricted input controls such as checkboxes, radio buttons, lists, combo boxes and spinners as well as free form controls such as text fields, password fields, formatted text fields and text boxes are highlighted.
Checkboxes
Checkboxes are used for selection of options. More than one option (or none) may be selected. JCheckBox() is used to construct these widgets. A checkbox widget is normally associated with a JLabel caption but can also be created by using a constructor with a caption parameter. The state of a checkbox can be found with a simple if (boxObject.getSelectedObjects() != null) test.
Often there is no need for checkbox events as their states are checked when a process button is selected. But there are times you may wish to update dynamically as an checkbox item is changed. This requires a different interface called ItemListener which responds to change of state rather than mouse clicks. The required implementation method is itemStateChanged(). A simple two checkbox example follows:
NOTE: Layout managers are explained in a following tutorial.
Radio Buttons
Radio buttons are used for selection of alternatives. Only one radio button may be selected at a time. JRadioButton is used to construct these widgets. A radio button is normally associated with a JLabel caption but can also be created using a constructor with a caption parameter. The state of a radio button can be found with the isSelected() method.
Button groups are used to ensure the mutual exclusivity of buttons in the group (ie. only one can be on at a time). Use ButtonGroup() to construct a button group and then add buttons with the add() method.
Borders are normally added to button groups for a visual separation. Unfortunately this doesn't work in Java! You must create a pane for the group and then add a border to the pane. For example:
NOTE: Layout managers are explained in a following tutorial.
List Boxes, Combo Boxes and Spinners
List boxes allow display and selection from a group of items. They are created with the JList() constructor which normally receives a list model as a parameter. List boxes are frequently constructed within JScrollPane containers to allow scrolling of lists longer than the display area.
List models provide methods for management of the elements of a list. The DefaultListModel class contains the constructor DefaultListModel(array) and management methods such as addElement(objName), elementAt{index], removeElement(objName), removeAllElements() and removeElementAt(idx). Status check methods include contains(objName), indexOf(name) and size(). Conversion to an array uses copyInto(array).
The currently selected element(s) can be found with getSelectedValue() or getSelectedIndex(). The setSelectionMode(selectionMode) method uses one of the following constants: ListSelectionModel.MULTIPLE_INTERVAL_SELECTION, ListSelectionModel.SINGLE__INTERVAL_SELECTION or ListSelectionModel.SINGLE_SELECTION. A default selection can be set with the setSelectedIndex(x)method. Multiply selected list items are returned as an array with the getSelectedValues() method. They are accessed with a loop and made into strings for viewing.
Several methods can be used to manipulate presentation of the list. setVisibleRowCount(x) sets the row count. The fOrientation (float orientation) property can be set to VERTICAL, VERTICAL_WRAP or HORIZONTAL_WRAP.
For a working example of a JList see Batch GUI File IO.
Combo boxes are lists that also have a text field for adding a selection. Combo boxes are created with the JComboBox() constructor. The method setEditable(true) makes combo box items editable. Selected items are recovered with the getSelectedItem() and getSelectedIndex() methods. Other useful methods are getItemAt(idx), getItemCount(), setSelectedItem(obj), and setMaximumRowCount(x).
Spinners are lists that have only one item visible at a time. Up and down arrows select from the list. No scroll bar is provided which minimizes the space occupied in the interface. The JSpinner class uses a JFormattedText field for display and editing.
Text Fields and Passwords
Single line free format text fields are created using the JTextField() constructor. A string value is returned. JPassWordField() is similar to JTextField() but displays any typed characters as asterisks for security. Text fields can also be used to display output information!
Formatted text fields allow display in a locale specific manner as well as restricting entry to valid characters. The class constructor used is JFormattedTextField(). Formats include: Date, Integer, Float, currency, percent and URI. Invalid input will be rejected. Up/down arrows cause some format data to alter by one. The escape key is used for canceling entries. You may want to download SimpleFTF.java to see how formatted text fields can be set up and how they are used
Text Areas
Text areas are editing areas for blocks or multiple lines of text. These can be constructed from JTextArea (simple text), JEditorPane (html, rtf and other formatted text), or JTextPane classes. Useful methods include getText(), setText(), append(str), insert(str,pos), replace(str,beg,end), setEditable(bool), setLineWrap(bool) and setWrapStyleWord(bool).
Often the data in a text area exceeds the display space available and a scrolling mechanism is required. By placing the text area component in a JScrollPane container any required scrollers will be automatically added. Fixed scrollers can be established as well. To set up a scrollable text region follow this example:
An example of a handy class for moving text area data to/from files is:
Note: The need to check for line termination which is platform dependent. Too bad something like File.separator does not exist!