JAVAFX 可编辑组合框给出空值

标签 java combobox javafx-8

<分区>

我遇到了一个奇怪的问题。我有一个包含一些项目的可编辑组合框。运行我的代码后,如果我在该 ComboBox 中键入内容并调用 getValue() 函数,那么它会给我 null值(value)。

这是我的代码 (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

最佳答案

根据 getValue() 的文档:

The value of this ComboBox is defined as the selected item if the input is not editable, or if it is editable, the most recent user action: either the value input by the user, or the last selected item.

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

因此,getValue() 将在这些情况下返回以下内容,并在考虑到这些细节后表现得完全符合预期:

  • 文本“文本”已输入但不接受操作键:null

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

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

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

comboBox.getEditor().getText();

关于JAVAFX 可编辑组合框给出空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35023980/

相关文章:

Java 默认图标集

vba - Excel组合框问题

jquery - 如何使用 jQuery UI 组合框创建新值

java - 如何将所有形状插入数组中?

java - 如何在 javaFx 中更新 java-124 版本后解决 TableView 中的嵌套列?

c# - 如何在 java 和 C# 中捕获和使用语音?

java - IIS 403 禁止在 URL 中使用 %2F

java - 使用一个参数在java中创建compareTo方法

java - 如何加载未选择任何值的枚举填充的组合框

java - 使用 Java Lambdas 替换 javafx 构建器