java JavaFX 2 ComboBox setValue() 不设置 CB 文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13483025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 12:56:00  来源:igfitidea点击:

JavaFX 2 ComboBox setValue() does not set CB text

javacomboboxjavafx-2

提问by Anvar

My problem is that the selected ComboBox item text is not visible on the screen after selecting it with setValue(). Here are some details: Adding items to my CB:

我的问题是所选的 ComboBox 项目文本在使用 setValue() 选择后在屏幕上不可见。以下是一些详细信息:将项目添加到我的 CB:

combo.getItems().add("a");
combo.getItems().add("b");
combo.getItems().add("c");
combo.getItems().add("d");

Afterwards, when Button A is pushed:

之后,当按下按钮 A 时:

combo.setValue(null);

When Button B is pushed:

当按下按钮 B 时:

combo.setValue("a");

Now, if I push Button B first, "a" is shown, thats OK. After that if I push Button A, no text is shown on the ComboBox, thats OK. Then I push B, and the value did not change on the screen. However, if I click on the CB, the row for "a" is highlighted, and combo.getValue() returns "a".

现在,如果我先按下按钮 B,会显示“a”,那没问题。之后,如果我按下按钮 A,组合框上不会显示任何文本,没关系。然后我按B,屏幕上的值没有改变。但是,如果我单击 CB,“a”的行会突出显示,并且 combo.getValue() 返回“a”。

Any suggestions how to handle this?

任何建议如何处理这个?

回答by Vertex

I have the same problem. It looks like a bug. Here is a full working example with a ComboBoxthat contains Locales:

我也有同样的问题。它看起来像一个错误。这是一个ComboBox包含Locales的完整工作示例:

package org.example;

import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.util.StringConverter;

public final class ComboBoxTest extends Application {
    @Override
    public void start(final Stage stage) throws Exception {
        // Initialize UI
        stage.setTitle("ComboBox Test");
        final HBox root = new HBox(5.0f);
        final ComboBox<Locale> cbLocales = new ComboBox<>();
        cbLocales.setConverter(new StringConverter<Locale>() {
            @Override
            public String toString(final Locale locale) {
                return locale.getDisplayName();
            }

            @Override
            public Locale fromString(String string) {
                throw new UnsupportedOperationException();
            }
        });
        cbLocales.setPrefWidth(250);
        HBox.setMargin(cbLocales, new Insets(10));
        root.getChildren().add(cbLocales);
        final Button btnFill = new Button("Fill");
        HBox.setMargin(btnFill, new Insets(10));
        root.getChildren().add(btnFill);
        final Scene scene = new Scene(root);
        stage.setScene(scene);

        btnFill.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(final MouseEvent event) {
                // Fill with content
                final List<Locale> locales = Arrays.asList(Locale.ENGLISH,
                        Locale.GERMAN, Locale.FRENCH);
                final Locale defaultLocale = locales.get(1);
                // cbLocales.getItems.setAll(locales) doesn't work
                cbLocales.getItems().clear();
                cbLocales.getItems().addAll(locales);
                // Set default locale
                cbLocales.setValue(defaultLocale);
                cbLocales.setPromptText(cbLocales.getConverter().toString(
                        cbLocales.getValue()));
            }
        });

        stage.show();
    }

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

When the ComboBoxfilled for the first time, all works fine: The ComboBoxcontains all 3 Locales and the second Localeis set.

ComboBox充满首次,一切工作正常:将ComboBox包含所有3Locale秒和第二Locale设置。

enter image description here

在此处输入图片说明

After filling a second time, ComboxBox.setValuedoesn't work: The ComboBoxcontains all 3 Locales but the second Localeis notset. No item is selected an no prompt is shown.

填充第二时间之后,ComboxBox.setValue不工作:ComboBox包含所有3Locale秒,但第二个Locale设置。未选择任何项目,不显示提示。

enter image description here

在此处输入图片说明

I fixed the prompt problem with

我修复了提示问题

// Set default locale
cbLocales.setValue(defaultLocale);
cbLocales.setPromptText(cbLocales.getConverter().toString(
        cbLocales.getValue()));

but it doesn't select the item in the list:

但它不会选择列表中的项目:

enter image description here

在此处输入图片说明

A work around is that:

解决方法是:

cbLocales.getSelectionModel().select(defaultLocale);
cbLocales.setPromptText(cbLocales.getConverter().toString(cbLocales.getValue()));

To select the item and set the prompt. But I don't know, if there are athor problems with that (tool tips or similar)

选择项目并设置提示。但我不知道,如果有问题(工具提示或类似的)

回答by invariant

When creating a combo box, you must instantiate the ComboBox class and define the items as an observable list, just like other UI controls such as ChoiceBox, ListView, and TableView.

创建组合框时,您必须实例化 ComboBox 类并将项目定义为可观察列表,就像其他 UI 控件(如 ChoiceBox、ListView 和 TableView)一样。

Sample Code :

示例代码:

ObservableList<String> options = 
    FXCollections.observableArrayList("A","B","C","D");

combo.setItems(options);

now results should be as u expected :) (tested on my local machine)

现在结果应该如你所料:)(在我的本地机器上测试)

Reference : Combo Box

参考: 组合框

回答by Martin Pfeffer

I recognized a strange behavior. It looks like the setItems()should not be done before you set your "value"... Here's some code which works for me:

我认出了一种奇怪的行为。看起来setItems()不应该在设置“值”之前完成......这是一些对我有用的代码:

 ComboBox<String> editableComboBox = new ComboBox<String>(); // <- setting the items here 
                                                             // brings the "bug"
    editableComboBox.setId("combobox_fields" + i);
    String desciption = pair.getDescription();
    editableComboBox.setValue(desciption);
    editableComboBox.setEditable(true); 
    editableComboBox.setItems(FieldType.FIELD_TYPES); // <- here we go!

And here the values..

这里的价值观..

public static final ObservableList<String> FIELD_TYPES =
            FXCollections.observableArrayList("A", "B", "C",
                                              "D", "E", "F",
                                              "G", "H", "I");