【问题标题】:How can I populate a ComboBox with Queue elements?如何使用 Queue 元素填充 ComboBox?
【发布时间】:2019-05-25 04:24:40
【问题描述】:

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

我正在使用 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],则组合框应按从上到下的顺序显示“求解”、“2.3”、“4.2”、“7.1”。

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

感谢任何解决方案。

【问题讨论】:

  • 我不确定将"Solve for" 包含为项目是否是个好主意。通常你使用在组合旁边放一个带有这样文本的标签,或者使用它的promptText 属性。 (如果您想允许用户通过选择此项来输入新元素,请忽略此注释。)

标签: java javafx combobox queue populate


【解决方案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());
}

【讨论】:

  • 非常感谢,您的解决方案很棒!
【解决方案2】:

考虑使用流:

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

【讨论】:

    猜你喜欢
    • 2011-04-01
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 2013-12-19
    • 2018-10-13
    • 1970-01-01
    • 2019-05-12
    • 2019-03-23
    相关资源
    最近更新 更多