Credits

Sunday, February 20, 2011

Java's Radio Buttons

Java's radio button functions like a check box  however unlike a check box, a radio button can only be selected once in a specific group.

A constructor for radio buttons can be as follows:


JRadioButton rb1=new JRadioButton("Red");
JRadioButton rb2=new JRadioButton("Blue");
JRadioButton rb3=new JRadioButton("Yellow");
ButtonGroup background=new ButtonGroup();
:
:
con.add(rb1);
con.add(rb2);
con.add(rb3);
:
:
//adding background color to the radio buttons
rb1.setBackground(Color.RED);
rb2.setBackground(Color.BLUE);
rb3.setBackground(Color.YELLOW);

background.add(rb1);
background.add(rb2);
background.add(rb3);

You can add an event on radio buttons using the ItemEvent. See the sample below.
[+/-] show/hide


/*JRadioButton with action events*/

/* sample use of JCheckbox with Item event */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JRadioButtonDemoEvent extends JFrame implements ItemListener{

Container con = getContentPane();
JRadioButton rb1=new JRadioButton("Red");
JRadioButton rb2=new JRadioButton("Blue");
JRadioButton rb3=new JRadioButton("Yellow");
ButtonGroup background=new ButtonGroup();


//constructor for JCheckBoxEvent

public JRadioButtonDemoEvent()
{ super("JRadioButton Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
con.setLayout(new FlowLayout());
con.add(rb1);
con.add(rb2);
con.add(rb3);

//adding background color to the radio buttons
rb1.setBackground(Color.RED);
rb2.setBackground(Color.BLUE);
rb3.setBackground(Color.YELLOW);

background.add(rb1);
background.add(rb2);
background.add(rb3);

//adding an item listener
rb1.addItemListener(this);
rb2.addItemListener(this);
rb3.addItemListener(this);



}

public void itemStateChanged(ItemEvent e){
ItemSelectable source;
source = e.getItemSelectable();

if (source==rb1){
con.setBackground(Color.RED);}
else if (source==rb2){
con.setBackground(Color.BLUE);}
else if (source==rb3){
con.setBackground(Color.YELLOW);}
}


public static void main (String[] args)
{ JFrame aFrame = new JRadioButtonDemoEvent();
aFrame.setSize(250,150);
aFrame.setVisible(true);
}}6

AddThis