Radio Button in Java Using Netbeans IDE

Introduction

This article describes how Radio Button can be created in Java. The Netbeans IDE is used for development of the example.

What is Radio Button

A Radio Button looks like a small circle which is used when we want the user to select one option from multiple alternatives.

Packages Imported

java.awt.*;

AWT stands for Abstract Window ToolKit, AWT is a class library that is provided by Java programming language. AWT includes all classes to write the program that acts as an interface between the user and various windowing toolkits. The AWT package can be used for development of user interface objects, like buttons, checkboxes, Radio Buttons, menus and so on.

javax.swing.*;

Swing is used to provide a graphical user interface to programs written using Java. Swing is an extended version of AWT, because it provides some extra components compared to AWT, like trees, scroll panes, tables and so on. Swing provides a native look and feel.

Advantages

The advantages of a Radio Button are:

  • Because of Radio Buttons the user can see all options at once, instead of finding them in a list.
  • Radio Buttons provide the feature of an easy comparison of choices to the user.
  • Due to Radio Buttons the user does not need to remember choices.
  • Radio Buttons provide easy access to choices.

Example

In this example; we create a Radio Button in Java using the Netbeans IDE. There are certain steps in the Netbeans IDE that we need to follow as explained below.

Step 1

Open the Netbeans IDE.

fig 1.jpg

Step 2

Click on "File" from the Menu bar as shown in the following:

fig 2.jpg

Step 3

Click on "New Project" as shown in the following:

fig 3.jpg

Step 4

Select "Java" and "Java application" as shown in the following:

fig 4.jpg

Step 5

Click "Next" as shown in the following:

fig 5.jpg

Step 6

Instead of the project name specify "JRdoBtn" and instead of main class also specify "JRdoBtn" and click on "Finish".

fig 6.jpg

Step 7

In this class write the following code (the class name is "JRdoBtn"): 

import javax.swing.*;

import java.awt.*;

public class JRdoBtn extends JFrame

{

public void launchFrame()

{

   setLayout(new FlowLayout());

JRadioButton b1=new JRadioButton("Male");

add(b1);

JRadioButton b2=new JRadioButton("Female");

add(b2);

ButtonGroup bg=new ButtonGroup();

bg.add(b1);

bg.add(b2);

   setSize(300,300);

setVisible(true);

}

public static void main(String[] args)

{

JRdoBtn obj=new JRdoBtn();

obj.launchFrame();

}

}

fig 7.jpg

Step 8

Now go to JRdoBtn and right-click on that, click on "Run" from the menu bar as in the following:

fig 8.jpg

Output

You can select any one of the Radio Buttons either male or female.

fig 9.jpg

 


Similar Articles