JavaFX Radio Button

0

JavaFX Radio Button tutorial :

JavaFX Radio Button mainly grouped together And user can do single selection from all of them.

Constructors of radio button :

  • RadioButton()Creates a radio button with an empty string for its label.
  • RadioButton(String text)Creates a radio button with the specified text as its label.

how to create radio button :

    • To give a permission of single selection to the use we group all radio button using Togglegroup AS

ToggleGroup group1 = new ToggleGroup();

    • To set a group of a radio button we use setToggleGroup(group) AS

Rbutton1.setToggleGroup(group);

  • To pre-select a radio button we use setSeleceted(true) method.

Example of radio button :


package javafxtuts;


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.stage.Stage;


/**
 *
 * @author javafxtuts
 */
public class Javafxtuts extends Application {
    
    

  @Override
  public void start(Stage primaryStage) {
      
      // setting title of application
      primaryStage.setTitle("javafxtuts.com");
      double width = 400;
      double height = 300;
      //Vbox layout
      VBox root = new VBox();
      //Creating a ToggleGroup
      ToggleGroup group=new ToggleGroup();
      
    //creating new radio buttons. 
      RadioButton rb1 = new RadioButton(" 1 ");
      RadioButton rb2 = new RadioButton(" 2 ");
      RadioButton rb3 = new RadioButton(" 3 ");
      // Set toggle group
      rb1.setToggleGroup(group);
      rb2.setToggleGroup(group);
      rb3.setToggleGroup(group);
      //pre select a radio button
      rb1.setSelected(true);
      root.setPadding(new Insets(10));
      
      //add all children of Vbox layout(root)
      root.getChildren().addAll(rb1,rb2,rb3);
      
      Scene scene = new Scene(root, width, height);
      primaryStage.setScene(scene);
      primaryStage.show();
  }
  

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
}

Output:

Explanation of radio button example :

    • Create a Toggle group AS

ToggleGroup group=new ToggleGroup();

    • Create a radio button AS

RadioButton rb1 = new RadioButton(" 1 ");

    • Set toggle group to a radio button AS

rb1.setToggleGroup(group);

    • To get pre selected radio button when application load use setSelected(true) method AS

rb1.setSelected(true);

Other methods:

  • WE can set image on radio button using setgraphics() method AS
Image image = new Image("one.jpg");
rb1.setGraphic(new ImageView(image));
  • isSelected() method return true if a particular radio button is selected by user.
  • We handle the action events using the changelistener for toggle group.
  • Share.

    Leave A Reply