Java Reference
In-Depth Information
Defining radio button groups
Some components require grouping in order to function. Mutually exclusive
radio buttons, for example, need to know about the group they belong to so that
the selection of one leads to the deselection of all other group members. Ten
radio buttons on a GUI might belong to one large group, five sets of two, or some
mix in between. This group relationship isn't visible or accessible in the Form
Workspace of the GUI Designer; you should implement it in the form class's con-
structor, an example of which is shown in listing 10.1.
Listing 10.1
Defining a group of radio buttons in a form class's constructor
...
public class SearchGUI {
private JRadioButton dirForward;
private JRadioButton dirBackward;
public SearchGUI() {
ButtonGroup searchDirection = new ButtonGroup();
searchDirection.add(dirForward);
searchDirection.add(dirBackward);
...
Implementing actions
Some components exist on the GUI to take action. For example, the Convert but-
ton on the ACME GUI is responsible for collecting the data on the form, executing
the business logic in the currency converter, and providing the results back to the
user through the GUI . This work has to be done programmatically, and it's
beyond the responsibility of the Form Workspace. It requires you to use the Swing
event-handling model and is another good candidate for implementation in the
form class's constructor.
To illustrate, imagine the simplistic GUI and use case that have been imple-
mented in listing 10.2. The GUI has a text field, a button, and a label. The user
types something in the text field and then clicks the button. The button's respon-
sibility is to check whether the data in the field is an integer value, as opposed to
textual or alphanumeric gibberish. The result of the test is shown in the label.
Listing 10.2
Defining the action for a “Check if this is an integer” button
...
checkButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String datum = datumField.getText();
 
 
Search WWH ::




Custom Search