JavaFX ChoiceBox create

Description

JavaFX ChoiceBox create

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage; 

public class Main extends Application { 
    Label genderLbl = new Label("Gender:"); 
    ChoiceBox<String> genderFld = new ChoiceBox<>(); 

    // Buttons //ww w. j a v a2  s .  co m
    Button saveBtn = new Button("Save"); 
    Button closeBtn = new Button("Close"); 

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

    @Override 
    public void start(Stage stage) throws Exception { 
        // Populate the gender choice box 
        genderFld.getItems().addAll("Male", "Female", "Unknown"); 

        GridPane grid = new GridPane(); 
        grid.setHgap(5); 
        grid.setVgap(5); 

        // Place the controls in the grid     
        grid.add(genderLbl, 0, 3); // column=0, row=3 
        grid.add(genderFld, 1, 3); // column=1, row=3 

        // Add buttons and make them the same width 
        VBox buttonBox = new VBox(saveBtn, closeBtn); 
        saveBtn.setMaxWidth(Double.MAX_VALUE); 
        closeBtn.setMaxWidth(Double.MAX_VALUE); 

        grid.add(buttonBox, 2, 0, 1, 2); // column=2, row=0, colspan=1, rowspan=2 

        // Show the data in the text area when the Save button is clicked 
        saveBtn.setOnAction(e -> showData()); 

        // Close the window when the Close button is clicked 
        closeBtn.setOnAction(e -> stage.hide()); 

        // Set a CSS for the GridPane to add a padding and a blue border 
        grid.setStyle("-fx-padding: 10;" 
                + "-fx-border-style: solid inside;" 
                + "-fx-border-width: 2;" 
                + "-fx-border-insets: 5;" 
                + "-fx-border-radius: 5;" 
                + "-fx-border-color: blue;"); 

        Scene scene = new Scene(grid); 
        stage.setScene(scene); 
        stage.setTitle("Person Details"); 
        stage.sizeToScene(); 
        stage.show(); 
    } 

    private void showData() { 
        String data = "\nGender=" + genderFld.getValue(); 
        System.out.println(data); 
    } 
} 



PreviousNext

Related