JavaFx Editable ComboBox : Showing toString on item selection

后端 未结 2 1508
南旧
南旧 2020-12-13 22:32

I have a ComboBox of type Person , in which I have added few object of Person class,

I have used setCellFa

2条回答
  •  臣服心动
    2020-12-13 23:10

    You need to set a StringConverter on the ComboBox for that purpose (there is no other way, looking at the source code of ComboBox)

    Here is an example:

    import javafx.application.Application;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.ComboBox;
    import javafx.stage.Stage;
    import javafx.util.StringConverter;
    
    import java.util.Arrays;
    import java.util.List;
    
    public class ComboBoxTest extends Application {
        private ComboBox cmb_year = new ComboBox<>();
    
        public static void main(String[] args) {
            launch(args);
        }
    
        @Override
        public void start(Stage primaryStage) throws Exception {
            Group root = new Group();
            root.getChildren().add(cmb_year);
            cmb_year.setPrefWidth(150);
            Scene scene = new Scene(root, 500, 500);
            primaryStage.setScene(scene);
            primaryStage.show();
    
            List ints = Arrays.asList(2012, 2013, 2014, 2015);
            cmb_year.getItems().addAll(ints);
    
            cmb_year.setConverter(
                new StringConverter() {
                    @Override
                    public String toString(Integer integer) {
                        if (integer == null) {
                            return "";
                        } else {
                            return "that's a year: " + integer.intValue();
                        }
                    }
    
                    @Override
                    public Integer fromString(String s) {
                        try {
                            return Integer.parseInt(s);
                        } catch (NumberFormatException e) {
                            return null;
                        }
                    }
                });
    
            cmb_year.setPromptText("select year");
            cmb_year.setEditable(true);
    
            Button distraction = new Button("distraction");
            distraction.setLayoutX(100);
            distraction.setLayoutY(100);
            root.getChildren().add(distraction);
        }
    }
    

    result:

    enter image description here enter image description here

提交回复
热议问题