by Dinesh Thakur

The ButtonGroup class allows to manage a set of buttons ensuring that only one button in the group will selected. To use the ButtonGroup class, simply instantiate an object and add buttons (objects that inherit from the class AbstractButton) through the add () method. It is preferable to use objects JToggleButton class or one of its subclasses because they are able to manage their states.

import java.awt.*;

import javax.swing.*;
import java.awt.event.*;
public class JavaExampleToggleGroupInJApplet extends JApplet
 {
    public JavaExampleToggleGroupInJApplet()
      {
        Container Cntnr = getContentPane();
        ButtonGroup BtnGrp = new ButtonGroup();
        JToggleButton[] Btns = new JToggleButton[]
          {
             new JToggleButton(new ImageIcon("Koala.jpg")),
             new JToggleButton(new ImageIcon("Koala.jpg")),
             new JToggleButton(new ImageIcon("Koala.jpg")),
             new JToggleButton(new ImageIcon("Koala.jpg")),
             new JToggleButton(new ImageIcon("Koala.jpg"))
           };
             Cntnr.setLayout(new FlowLayout());
             for(int l=0; l < Btns.length; ++l)
               {
                   BtnGrp.add(Btns[l]);
                   Cntnr.add(Btns[l]);
                }
      }
 }
/*<APPLET CODE=JavaExampleToggleGroupInJApplet.class WIDTH=300 HEIGHT=200 > </APPLET>*/

Java JToggleButton Group Example