How to Create a RadioButton using Java

Swing – Create a RadioButton using Java

In this example, We will show simple swing program about, How to create a RadioButton using Java. This example program has been tested and shared with the output in the same post.

Sample Program

package com.dineshkrish;

import java.awt.BorderLayout;

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class RadioButtonExample extends JFrame {

	private JPanel panel;
	private ButtonGroup gender;

	private JRadioButton male;
	private JRadioButton female;

	public RadioButtonExample(String title) {

		// setting window properties
		super.setTitle(title);
		super.setDefaultCloseOperation(EXIT_ON_CLOSE);
		super.setSize(300, 100);
		super.setVisible(true);

		// setting the layout
		super.setLayout(new BorderLayout());

		init();
	}

	private void init() {

		panel = new JPanel();

		gender = new ButtonGroup();

		male = new JRadioButton("Male");
		female = new JRadioButton("Female");

		// adding radio buttons to button group
		gender.add(male);
		gender.add(female);

		panel.add(male);
		panel.add(female);

		add(panel, BorderLayout.NORTH);
	}

	public static void main(String[] args) {

		new RadioButtonExample("Radio Button Example");
	}
}

Output

How to Create a RadioButton using Java

Hello, folks, I am a founder of dineshkrish.com. I love Java and Open source technologies, If you find my tutorials are useful, please consider making donations to these charities.