JAVAFX Editable Combobox给出null值

时间:2016-01-26 21:07:50

标签: java combobox javafx-8

我面临一个奇怪的问题。我有一个可编辑的ComboBox和一些项目。运行我的代码后如果我在ComboBox中键入内容并调用 getValue() 函数,那么它会给我 null 值。

这是我的代码(thenewboston): 包裹申请;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {

    Stage window;
    Scene scene;
    Button button;
    ComboBox<String> comboBox;

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

    @Override
    public void start(Stage primaryStage) throws Exception {
        window = primaryStage;
        window.setTitle("ComboBox Demo");
        button = new Button("Submit");

        comboBox = new ComboBox<>();
        comboBox.getItems().addAll(
                "Good Will Hunting",
                "St. Vincent",
                "Blackhat"
        );

        comboBox.setPromptText("What is your favorite movie?");
        comboBox.setEditable(true);
        button.setOnAction(e -> printMovie());

        //ComboBoxes also generate actions if you need to get value instantly
        comboBox.setOnAction( e -> System.out.println("User selected " + comboBox.getValue()) );

        VBox layout = new VBox(10);
        layout.setPadding(new Insets(20, 20, 20, 20));
        layout.getChildren().addAll(comboBox, button);

        scene = new Scene(layout, 300, 250);
        window.setScene(scene);
        window.show();
    }
    private void printMovie(){
        System.out.println(comboBox.getValue());
    }
}

我使用的是Windows 8.1,Eclipse Mars(4.5)和Java 1.8.0_66

1 个答案:

答案 0 :(得分:6)

根据getValue()的文档:

  

如果是,则将此ComboBox的值定义为所选项   输入不可编辑,或者如果可编辑,则为最新用户   action:用户输入的值或最后选择的项目。

getValue()将不会返回“用户输入的值”,直到用户使用操作键(通常是键盘上的Enter键)接受其输入文本。

因此,getValue()将在这些场景中返回以下内容,并且在完成预期时会考虑到以下细节:

  • 输入文字“text”,但不接受操作键: null

  • 文字,“文字”,输入到组合框中,并被接受 操作键:文字

  • 选择下拉组合项目“Good Will Hunting”: Good Will Hunting

一旦用户接受了使用操作键输入的文本,将返回正确的值而不是null。如果您想将实际文本输入到组合框中,您可以考虑检索组合框编辑器的当前值:

comboBox.getEditor().getText();
相关问题