如何使用队列元素填充组合框?

How can I populate a ComboBox with Queue elements?

一段时间以来,我一直在努力弄清楚如何使用队列中的多个元素填充组合框。谁能告诉我怎么做?

我正在使用 JavaFX(无场景生成器)和最新版本的 Java。我试过使用迭代器,但我只能成功地将一个元素填充到组合框中。

i1.getItems().addAll ( //combobox code
            "Solve for",
        //queue elements here
);


//interator code. Other class calls it.
itrVelocity = velAns.iterator();

    while (itrVelocity.hasNext()) {
        SPH3U.velocity = itrVelocity.next();
    }

如果队列中有以下元素[2.3, 4.2, 7.1],则组合框应按从上到下的顺序显示"Solve for",“2.3”,“4.2”,“7.1”。

但是,我只成功地让组合框显示 "Solve for"、“7.1”。

感谢任何解决方案。

您应该只需要迭代 Queue 并将元素放入 ObservableList

ComboBox<String> box = new ComboBox<>();
box.getItems().add("Solve for");

// Assuming generic type of Queue based on your question
Queue<Double> queue = ...; // get instance from somewhere
while (!queue.isEmpty()) {
    box.getItems().add(queue.remove().toString());
}

或者,如果您不想耗尽 Queue,您可以这样做:

for (Double element : queue) {
    box.getItems().add(element.toString());
}

考虑使用流:

    ComboBox<String> cBox = new ComboBox<>();
    cBox.getItems().add("Solve for");
    cBox.getItems().addAll(queue.stream().map(String::valueOf).
                                                       collect(Collectors.toList()));