JavaFx:How to use radioButton in Java Fx?
For creating a file chooser you should have a structure as provided below in JavaFx project.
We have created this checkbox Java Fx programme to select single value from two radio button options.You can modify code according to your requirement.
Main.java
package application;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Parent;
import javafx.scene.Scene;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
Parent root=FXMLLoader.load(getClass().getResource("/application/Main.fxml"));
Scene scene = new Scene(root,400,400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
MainController.java
package application;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
public class MainController {
@FXML private RadioButton rb1;
@FXML private RadioButton rb2;
@FXML private Label lbl;
public void radioSelected (ActionEvent event){
String message="";
if(rb1.isSelected()){
message=message+rb1.getText()+"\n";
}
if(rb2.isSelected()){
message=message+rb2.getText()+"\n";
}
lbl.setText(message);
}
}
Main.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.RadioButton?>
<?import javafx.scene.control.ToggleGroup?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="300.0" prefWidth="300.0" xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.MainController">
<children>
<RadioButton fx:id="rb1" layoutX="29.0" layoutY="52.0" mnemonicParsing="false" onAction="#radioSelected" text="Male">
<toggleGroup>
<ToggleGroup fx:id="group" />
</toggleGroup>
</RadioButton>
<RadioButton fx:id="rb2" layoutX="29.0" layoutY="98.0" mnemonicParsing="false" onAction="#radioSelected" text="Female" toggleGroup="$group" />
<Label fx:id="lbl" layoutX="36.0" layoutY="171.0" prefHeight="35.0" prefWidth="124.0" />
</children>
</AnchorPane>
Note
No comments:
Post a Comment