Creating a JRadioButton
In Swing, the JRadioButton allows the user to select, or un-select, an item which is displayed. Only one of a group of round bullet buttons can be selected, such as selecting one station button on a car radio. You have most likely seen the use of radio buttons in on-line quizzes, tests, or practice web pages.
Each circle is one JRadioButton.
The chosen JRadioButton displays a dot inside the circle.
|
Radio buttons are dependent upon one another. |
|
A "group" of radio buttons is presented to the user and the user is asked to pick only one of the radio button choices. Due to this dependent relationship between the radio buttons, it is necessary to create this "grouped" dependency within the coding by using ButtonGroup.
ButtonGroup group = new ButtonGroup();
group.add(Button1);
group.add(Button2);
The radio buttons are "added" to the ButtonGroup and they are also "added" to the JPanel. The ButtonGroup is NOT "added" to the JPanel.
Create and Activate Radio Buttons: |
|
|
When creating interactive components, the interface ActionListener will be needed so that the event created by the circle "dot" (in this example) can be activated.
Remember that import java.awt.event.*; will be needed.
Steps to Establishing Active Radio Buttons:
1. Indicate the class "implements ActionListener"
2. Declare (name) the radio buttons
3. Create "new" radio buttons and label them
Warning: Do not re-declare these variables! (see more at end of page)
4. Create a new ButtonGroup
5. Add the radio buttons to the group
6. Attach "action" to the radio buttons ("addActionListener(this)")
7. Add components to the JPanel
8. Establish action to be taken method ("actionPerformed")
Remember that when a JRadioButton is "dotted",
an event will be generated and something will happen. |
Example: A mathematical computation appears as the question. Three possible choices are listed as the answer. The user must choose ONE of the possible answers. If the user's choice is correct, the question will be replaced with the message "Correct!!". If the user's choice is not correct, the message will be "Sorry, that is incorrect".
Common Error:
Re-declaring variables may create Null Exception Errors - be careful!