Thursday, 15 October 2015

Radio Button In JavaFx

When we want to select one option at a time we can create radio button because it provides series of items and use have choice to select any one when any of the option in radio button is selected actionevent is generated.

toogleGroup:

public final ObjectProperty<ToggleGroup> toggleGroupProperty

By using toogle group property we can detect which option is selected by user.

RADIO BUTTON IN JAVAFX:

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Font;
import javafx.stage.Stage;


public class mainfx extends Application 
{
RadioButton rad = new RadioButton("Small Size");
RadioButton rad1 = new RadioButton("Medium Size");
RadioButton rad2 = new RadioButton("Large Size");
ToggleGroup group = new ToggleGroup();
Label l1 = new Label("SELECT SIZE OF TEXT");
Label l2 = new Label("This is a text");

@Override
public void start(Stage primaryStage)
 {

Group root = new Group();      


primaryStage.setTitle("RADIO BUTTON");
GridPane grid = new GridPane(); 
rad.setToggleGroup(group);
rad1.setToggleGroup(group);
rad2.setToggleGroup(group);
rad.setUserData("First Option");
rad1.setUserData("Second Option");
rad2.setUserData("Third Option");
grid.setHgap(20);
grid.setVgap(20);
grid.add(l1, 1, 0);
grid.add(rad, 0, 1);
grid.add(rad1, 1, 1);
grid.add(rad2, 2, 1);
grid.add(l2, 1, 2);
Scene scene = new Scene(grid, 300, 250);
primaryStage.setScene(scene); 
primaryStage.show();
group.selectedToggleProperty().addListener(new ChangeListener<Toggle>(){
@Override
public void changed(ObservableValue<? extends Toggle> ov,
Toggle old_toggle, Toggle new_toggle) {
if (group.getSelectedToggle() != null) {
}   
String a=(group.getSelectedToggle().getUserData().toString());
if(a.equals("First Option"))
{
l2.setFont(new Font("Arial",15));
}


else if(a.equals("Second Option"))
{
l2.setFont(new Font("Arial",25));
}


else if(a.equals("Third Option"))
{
l2.setFont(new Font("Arial",35)); 
}
}
});

}
public static void main(String[] args) 
{
launch(args);
}

}

OUTPUT:



No comments:

Post a Comment