Stage.show()更改ComboBox的值

时间:2016-08-26 10:16:16

标签: java javafx combobox stage

考虑以下MCVE。当然,这个MCVE的功能完全没有意义,但我需要它在实际实现中以这种方式工作。

import javafx.application.Application;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

@SuppressWarnings("all")
public class MCVE extends Application {

    private static final String OPTION_1 = "Option 1 (www.option1.com)";
    private static final String OPTION_2 = "Option 2 (www.option2.com)";
    private static final String OPTION_3 = "Option 3 (www.option3.com)";
    private static final String OPTION_4 = "Option 4 (www.option4.com)";
    private static final String OPTION_5 = "Option 5 (www.option5.com)";

    ComboBox<String> cb;

    @Override
    public void start(Stage primaryStage) throws Exception {
        VBox outer = new VBox();

        cb = new ComboBox<String>();
        outer.getChildren().add(cb);

        Scene scene = new Scene(outer, 640, 480);
        primaryStage.setScene(scene);

        Task<Void> task = new Task<Void>() {
            @Override
            public Void call() {
                cb.getItems().addAll(OPTION_1, OPTION_2, OPTION_3, OPTION_4, OPTION_5);
                cb.setEditable(true);

                // Adds a listener to the selectedItemProperty that gets the
                // value inside the parenthesis of the selected item and sets
                // this as the text of the ComboBox.
                cb.getSelectionModel().selectedItemProperty().addListener((obs, oldValue, newValue) -> {
                    String[] valSplit = newValue.split("[\\(\\)]");
                    if (valSplit.length > 1) {
                        Platform.runLater(() -> cb.getEditor().setText(valSplit[1]));
                    }
                });

                cb.getEditor().textProperty().addListener((obs, oldValue, newValue) -> {
                    System.out.println("CB value: " + newValue);
                });

                setURL("www.option2.com");

                return null;
            }
        };

        task.setOnSucceeded(e -> {
            primaryStage.show();
        });

        new Thread(task).start();
    }

    public void setURL(String url) {
        // First we check if the classValue is the URL of one of the options in
        // the ComboBox. If it is we select that option.
        for (String option : cb.getItems()) {
            // We retrieve the URL of the option.
            String opURL = option.split("[\\(\\)]")[1];
            // If the URL of the option is equals to the provided URL, we select
            // this option and break the for loop.
            if (opURL.equals(url)) {
                cb.getSelectionModel().select(option);
                break;
            }
        }
    }

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

由于我调用setURL("www.option2.com"),我希望它首先在ComboBox中选择带有该URL的选项,然后在括号内获取值并将其设置为{{1}的文本}}。所以我除了ComboBox的最终价值是“www.option2.com”。但这不会发生。相反,最终值是“选项2(www.option2.com)”。

由于我已经向ComboBox的{​​{1}}添加了一个监听器,我可以看到该值首先是预期的“www.option2.com”,但后来又变回“选项2” (www.option2.com)”。经过一些进一步的调查后,我发现调用textProperty会改变价值。更具体地说,它是调用已弃用的ComboBox来更改值。

因此,如果我在primaryStage.show()之后设置了网址,那么一切都可以正常工作。但是,如果我想在显示对话框之前完成所有工作,就像我现在所做的那样,事实并非如此。

那么为什么Parent.impl_processCSS会更改primaryStage.show()的值,我该怎样阻止这个?在尝试设置primaryStage.show()的值时,我是否可以使用其他方法?

1 个答案:

答案 0 :(得分:1)

您可以与代码ComboBox的{​​{3}}的文本交换部分代码,其中包含设置editorcell factory的代码。< / p>

cb.setConverter(new StringConverter<String>(){
    @Override
    public String toString(String object) {
        if(object != null) {
            String[] valSplit = object.split("[\\(\\)]");
            return valSplit[1];
        } else 
            return null;

    }

    @Override
    public String fromString(String string) {

        List<String> collect = cb.getItems().stream().filter(s -> s.contains(string)).collect(Collectors.toList());
        if(collect.size() == 1)
            return collect.get(0);
        else
            return null;
    }
});

cb.setCellFactory(item -> {
    return new ListCell<String>(){
        @Override
        protected void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);

            if(item == null || empty)
                setText("");
            else
                setText(item);
        }
    };
});

转换器的toString方法将格式化所需表单中的所选项目,单元格工厂可确保下拉列表中的项目以原始格式显示。

注意:我还填写了转换器的fromString方法。执行此方法,当用户键入编辑器然后按enter。此实现检查列表中的所有项目,如果只有一个项目包含键入的字符串,则将选择该项目。