JavaFX - RadioButton



A button is a component, which performs an action like submit and login when pressed. It is usually labeled with a text or an image specifying the respective action. A radio button is a type of button, which is circular in shape. It has two states, selected and deselected. The figure below shows a set of radio buttons −

JavaFX Radio Button

RadioButton in JavaFX

In JavaFX, the RadioButton class represents a radio button which is a part of the package named javafx.scene.control. It is the subclass of the ToggleButton class. Action is generated whenever a radio button is pressed or released. Generally, radio buttons are grouped using toggle groups, where you can only select one of them. We can set a radio button to a group using the setToggleGroup() method.

To create a radio button, use the following constructors −

  • RadioButton() − This constructor will create radio button without any label.

  • RadioButton(String str) − It is the parameterized constructor which constructs a radio button with the specified label text.

Example

Following is the JavaFX program that will create a RadioButton. Save this code in a file with the name JavafxRadiobttn.java.

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class JavafxRadiobttn extends Application {
   @Override
   public void start(Stage stage) {
      //Creating toggle buttons
      RadioButton button1 = new RadioButton("Java");
      RadioButton button2 = new RadioButton("Python");
      RadioButton button3 = new RadioButton("C++");
      //Toggle button group
      ToggleGroup group = new ToggleGroup();
      button1.setToggleGroup(group);
      button2.setToggleGroup(group);
      button3.setToggleGroup(group);      
      //Adding the toggle button to the pane
      VBox box = new VBox(5);
      box.setFillWidth(false);
      box.setPadding(new Insets(5, 5, 5, 50));
      box.getChildren().addAll(button1, button2, button3);
      //Setting the stage
      Scene scene = new Scene(box, 400, 300, Color.BEIGE);
      stage.setTitle("Toggled Button Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

Compile and execute the saved Java file from the command prompt using the following commands −

javac --module-path %PATH_TO_FX% --add-modules javafx.controls JavafxRadiobttn.java
java --module-path %PATH_TO_FX% --add-modules javafx.controls JavafxRadiobttn

Output

On executing, the above program will generate the following output −

RadioButton Output
Advertisements