In this tutorial you will learn about the Swing JRadioButton and its application with practical example.
Swing JRadioButton
The JRadioButton class is used to create radio button. It’s an implementation of a radio button. This radio button are used for selecting one option from multiple choice. Used with a ButtonGroup object to create a group of button in which only one button at a time can be selected.
JRadioButton Class Declaration
1 |
public class JRadioButton extends JToggleButton implements Accesible |
JRadioButton Constructor
Let’s get more understand about JRadioButton, Some of important constructor are listed below.
JRadioButton () : This constructor construct a new radio button with unselected state and no text , no icon.
JRadioButton (String text): This constructor construct a new radio button with unselected state and with text.
JRadioButton (Icon icon): This constructor construct a new radio button with unselected state and with icon.
JRadioButton (String text, boolean selected): This constructor construct a new radio button with text and specify whether or not it is initially selected.
JRadioButton (String text, Icon icon): This constructor is used to construct a new radio button with text and with icon.
JRadioButton (String text, Icon icon, boolean selected): This constructor is used to construct a new radio button with text, icon and specify whether or not it is initially selected.
JRadioButton (Action a): Construct a radio button where properties are taken from the Action supplied.
JRadioButton Methods
Some of commonly used methods are listed below. It will help to know more about JRadioButton.
AccessibleContext getAccessibleContext(): Used to gets the AccessibleContext which is associated with this JRadioButton.
void updateUI(): This method is used to resets the UI property to a value from the current look and feel.
protected String paramString(): This method returns string representation of this JRadioButton.
Example :-
An simple example to get understand about JRadioButton. Hopefully this will work for you.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
package w3addaswing; import javax.swing.ButtonGroup; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JRadioButton; public class W3ADDASwing { W3ADDASwing() { JFrame frame = new JFrame("RadioButton Example W3Adda"); JRadioButton r_male = new JRadioButton("A) Male"); JRadioButton r_female = new JRadioButton("B) Female"); r_male.setBounds(15, 50, 100, 30); r_female.setBounds(100, 50, 100, 30); ButtonGroup btn_grp = new ButtonGroup(); btn_grp.add(r_male); btn_grp.add(r_female); frame.add(r_male); frame.add(r_female); frame.setSize(400, 400); frame.setLayout(null); frame.setVisible(true);; } public static void main(String[] args) { // TODO code application logic here new W3ADDASwing(); } } |
Output :-
Output of this code will look like below image. You just need to copy this code and paste it in you program.