javaFX使用枚举实现html中下拉框功能

时间:2022-07-25 17:00:50
package sample;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import  javafx.scene.*;

import java.io.FileInputStream;
import java.net.URL;

/**
 * @author lq
 * 创建时间 2019/4/12 0:46
 **/
public class FXMLExample4 extends Application {

    enum  City {
        BEIJING(1,"北京"),SHANGHAI(2,"上海"),GUANGZHOU(3,"广州");

        int id;
        String name;

        City() {

        }
        City(int id,String name){
            this.id = id;
            this.name = name;
        }

        @Override
        public String toString() {
            return this.name;
        }
    }

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

    ObservableList cursors = FXCollections.observableArrayList(
            City.BEIJING,
            City.SHANGHAI,
            City.GUANGZHOU
    );

    /**
     * 类似html下拉框,使用枚举类型
     * @param primaryStage
     * @throws Exception
     */
    @Override
    public void start(Stage primaryStage) throws Exception {

            ChoiceBox choiceBoxRef = ChoiceBoxBuilder.create()
                    .items(cursors)
                    .build();

            VBox box = new VBox();
            box.getChildren().add(choiceBoxRef);
            final Scene scene = new Scene(box,300, 250);
            scene.setFill(null);
            primaryStage.setScene(scene);
            primaryStage.show();

            choiceBoxRef.setOnAction(event -> {
                City value = (City) choiceBoxRef.getValue();
                System.out.println(value.id);
            });

        }
}