by Dinesh Thakur Category: Swing

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



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Related Articles