java - 如何重置ComboBox并显示PromptText?

标签 java javafx combobox

注意: 我正在扩展重复的问题 here因为它不包含 MCVE。我发现的其他几个类似问题也不包含有效的答案。

我无法找到一种方法让 ComboBox 在清除选择后显示 PromptText

这是 MCVE:

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {

        final VBox root = new VBox(10);
        root.setAlignment(Pos.TOP_CENTER);
        root.setPadding(new Insets(10));

        final ComboBox<String> cboSelection = new ComboBox<>();
        final Button btnClear = new Button("Clear");

        // Set ComboBox selections
        final ObservableList<String> subjectsList = FXCollections.observableArrayList();
        subjectsList.addAll("Software", "Math", "Physics");

        // Setup the Subject selection
        cboSelection.setPromptText("Select Subject");
        cboSelection.setItems(subjectsList);

        // Set action for "Clear" button
        btnClear.setOnAction(e -> {
            cboSelection.setValue(null);
        });

        root.getChildren().addAll(cboSelection, btnClear);

        primaryStage.setTitle("ComboBox Demo");
        primaryStage.setScene(new Scene(root, 200, 100));
        primaryStage.show();


    }


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

}

单击“清除”按钮会将所选值设置为null并清除ComboBox的选择,但提示文本不再显示。这看起来不像正常的预期行为。

我已经在按钮的onAction中尝试了clearSelection()以及setPromptText(),但似乎没有任何方法可以获取提示文本返回。

最佳答案

根据documentation ,提示文本实际上根本不应该显示在此处:

Prompt text is not displayed in all circumstances, it is dependent upon the subclasses of ComboBoxBase to clarify when promptText will be shown. For example, in most cases prompt text will never be shown when a combo box is non-editable (that is, prompt text is only shown when user input is allowed via text input).

如果您想在选择为空时看到一些提示文本(并且您没有可编辑的组合框),请在组合框上使用自定义 buttonCell:

    cboSelection.setPromptText("Select Subject");
    cboSelection.setButtonCell(new ListCell<String>() {
        @Override
        protected void updateItem(String item, boolean empty) {
            super.updateItem(item, empty) ;
            if (empty || item == null) {
                setText("Select Subject");
            } else {
                setText(item);
            }
        }
    });

请注意,您似乎还需要设置提示文本(如问题中的代码所示),以便最初显示文本。我认为这是由于相同的错误(我猜测库代码最初错误地将按钮单元格的文本设置为提示文本;如果未设置提示文本,则文本将设置为 null ,显然是在调用按钮单元格的更新方法之后。

显然,您可以通过创建 ListCell 的命名子类来使其可重用:

public class PromptButtonCell<T> extends ListCell<T> {

    private final StringProperty promptText = new SimpleStringProperty();

    public PromptButtonCell(String promptText) {
        this.promptText.addListener((obs, oldText, newText) -> {
            if (isEmpty() || getItem() == null) {
                setText(newText);
            }
        });
        setPromptText(promptText);
    }

    public StringProperty promptTextProperty() {
        return promptText ;
    }

    public final String getPromptText() {
        return promptTextProperty().get();
    }

    public final void setPromptText(String promptText) {
        promptTextProperty().set(promptText);
    }

    @Override
    protected void updateItem(T item, boolean empty) {
        super.updateItem(item, empty);
        if (empty || item == null) {
            setText(getPromptText());
        } else {
            setText(item);
        }
    }
}

然后就

cboSelection.setButtonCell("Select Subject");
cboSelection.setButtonCell(new PromptButtonCell<>("Select Subject"));

关于java - 如何重置ComboBox并显示PromptText?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50569330/

相关文章:

javafx - FXML 文档中 Anchorpane 的代码设置背景颜色

javascript - 如何获取 ExtJS Combobox 的选定索引

objective-c - NSComboBox - 如何为 2 个不同的组合框实现委托(delegate)?

java - 堆栈和队列考试后续

java - 如何告诉这个Java方法在某种条件下再次执行自己?

java - Spring 启动器 : Missing Bean instead of missing value

JavaFx - SceneBuilder 中的 Tab 键顺序

JavaFX 测试应用程序是作为一个整体关闭还是只是单个窗口关闭

c# - WPF ComboBox : static list of ComboBoxItems, 但数据绑定(bind) SelectedItem?

用于跨平台应用程序的 JavaFX 2.0 和 Qt