Java Reference
In-Depth Information
In the preceding code, the question “What is your gender?” has the responses “female,”
“male,” or “not telling.” The response at position 2, “not telling,” is the default.
The SurveyPanel constructor uses a label component to hold the question and an array
of radio buttons to hold the responses:
SurveyPanel(String ques, String[] resp, int def) {
question = new JLabel(ques);
response = new JRadioButton[resp.length];
// more to come
}
The class uses grid layout to arrange its components into a grid with three vertical rows
and one horizontal column. Each component placed in the grid is a panel.
First, a panel is created to hold the question label:
JPanel sub1 = new JPanel();
JLabel quesLabel = new JLabel(ques);
sub1.add(quesLabel);
The default layout for panels, flow layout with centered alignment, determines the place-
ment of the label on the panel.
Next, a panel is created to hold the possible responses. A for loop iterates through the
string array that holds the text of each response. This text is used to create a radio button.
The second argument of the JRadioButton constructor determines whether it is selected.
This is implemented with the following code:
JPanel sub2 = new JPanel();
for (int i = 0; i < resp.length; i++) {
if (def == i) {
response[i] = new JRadioButton(resp[i], true);
} else {
response[i] = new JRadioButton(resp[i], false);
}
group.add(response[i]);
sub2.add(response[i]);
}
The last panel holds the Next and Finish buttons:
JPanel sub3 = new JPanel();
nextButton.setEnabled(true);
sub3.add(nextButton);
finalButton.setEnabled(false);
sub3.add(finalButton);
Search WWH ::




Custom Search