JRadioButtons in Java Swing

Home  »  Java  »  Advance Java »  »  Swing »  JRadioButtons

In AWT, radio buttons are check boxes that belongs to the same CheckboxGroup, which ensures that only one check box is selected at a time.

Radio buttons are implemented in Swing through the JRadioButton class. The constructor methods are the same as those for the JCheckBox class.

Example:

The following example creates two radio buttons one with a text and the other with a text and an icon displayed on it.



The following table describes some of the methods provided by the JRadioButton class

MethodsDescription
String getLabel()
void setLabel(String)
Sets or gets a label for a radio box
boolean getState()
void setState(Boolean)
Set or gets the status of the radio box


Example:

The following example creates four radio buttons, of which one pair will have an icon. The others will have the traditional radio button shown. By default the first and the last radio butons are checked, while the others are not checked. The example uses a method called 'setSelectedIcon()' which is used to replace the previous gif with the gif passed as a parameter to the method. This is done to show that the radio button is selected.

For example in the following code, radio button rbIconLeft displays an icon 'Back_up.gif'. This icon represents a back arrow. When this radio button is selected, the method setSelectedIcon() is used which sets 'Back_up.gif' to 'Back_sel.gif' to specify that the radio button is selected.



C:\>jdk1.4\bin>javac JRadioButtonsDemo.java
C:\>jdk1.4\bin>java JRadioButtonsDemo

"Output of JRadioButtonsDemo.class"


Download Complete Program

  -    -  Images




Java Swing-1


JFrame JPanel JApplet
JButtons JLabels JTextFields
JPasswordField JTextAreas JCheckBoxes
JRadioButtons JList JComboBox




No comments:

Post a Comment