RadioButton in Java AWT


Radio buttons provide a more user friendly environment for selecting only one option among many. It is a special kind of checkbox that is used to select only one option.

This is a Java program that demonstrates the use of Radio Buttons in AWT (Abstract Window Toolkit) for creating a simple GUI application.

  • The program creates a window using the Frame class and sets its size and layout. It then creates two Checkbox objects with a CheckboxGroup object to make them mutually exclusive. Two Label objects are created to display the state of the selected Checkbox object.
  • The program adds ItemListener objects to each Checkbox object to detect when its state changes (i.e., when it is selected or deselected). When a Checkbox is selected, its corresponding Label is updated to display the state change, and the other Label is set to "unchecked".
  • Finally, the program adds the Checkbox and Label objects to the window and sets a WindowAdapter object to handle the closing of the window when the user clicks on the close button.

Overall, this program shows how to use Radio Buttons in AWT to create a simple GUI application with event handling.

Source Code

package awtDemo;
 
import java.awt.*;
import java.awt.event.*;
//RadioButton in AWT
class MyApp  extends Frame{
 
	Label l1,l2;
	Checkbox c1, c2;
	CheckboxGroup cbg;
 
	public MyApp() {
		super("Tutor Joes");
		setSize(1000,600);//w,h
		setLayout(null);
		setVisible(true);
 
 
		cbg = new CheckboxGroup();
 
		c1 = new Checkbox("Male",cbg,false);
		c1.setBounds(10, 50, 250, 30);
 
		l1 = new Label("Not Selected");
		l1.setBounds(300, 50, 600, 30);
 
		c2 = new Checkbox("Female",cbg,false);
		c2.setBounds(10, 100, 250, 30);
 
		l2=new Label("Not Selected");
		l2.setBounds(300,100,600,30);
 
		c1.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				l1.setText((e.getStateChange() == 1 ? "checked" : "unchecked"));
				l2.setText("unchecked");
			}
		});
		c2.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
 
				l1.setText("unchecked");
				l2.setText((e.getStateChange() == 1 ? "checked" : "unchecked"));
			}
		});
 
		add(c1);
		add(l1);
		add(c2);
		add(l2);
 
		//Close Button Code
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent we) {
				System.exit(0);
			}
		});
	}
}
public class app{
	public static void main(String[] args) {
		MyApp frm=new MyApp();
	}
 
}
 
To download raw file Click Here

Output

Java AWT


Basic Programs