JavaFx ListView,获取列表中单元格的文本值

标签 java listview javafx cucumber

我正在尝试获取 ListView 中所选单元格的文本,因为它显示在 JavaFx 应用程序上。

这样做的目的是修复我在编写应用程序时遇到的一个错误。当底层模型更改时,ListView 中单元格的文本将无法正确更新。这在过去是有效的。 我正在尝试编写一个 cucumber 验收测试,这样如果它再次发生,错误就会被捕获。

下面是这个特定场景的stepdef。

@Given("^I have selected an item from the list display$")
public void I_have_selected_an_item_from_the_list_display() throws Throwable {
    ListView displayList = (ListView) primaryStage.getScene().lookup("#displayList");
    displayList.getSelectionModel().select(0);
}

@When("^I edit the items short name$")
public void I_edit_the_items_short_name() throws Throwable {
    fx.clickOn("#projectTextFieldShortName").type(KeyCode.A);
    fx.clickOn("#textFieldLongName");
}

@Then("^the short name is updated in the list display$")
public void the_short_name_is_updated_in_the_list_display() throws Throwable {
    ListView displayList = (ListView) primaryStage.getScene().lookup("#displayList");
    String name = "";
    // This gets me close, In the debuger the cell property contains the cell I need, with the text
    Object test = displayList.getChildrenUnmodifiable().get(0);

    //This will get the actual model object rather than the text of the cell, which is not what I want.
    Object test2 = displayList.getSelectionModel().getSelectedItem();

    assertTrue(Objects.equals("Testinga", name));
}

我浏览了 ListView JavaDoc,但找不到任何可以获取单元格文本的方法。

最佳答案

如果您有一个 ListView,那么单元格中显示的文本是在模型对象上调用 toString() 的结果,或者您已经设置了一个单元格ListView 上的工厂。对于后一种情况,只需重构逻辑以将显示文本放入单独的方法中即可:

ListView<MyModelObject> listView = ... ;

listView.setCellFactory(lv -> new ListCell<MyModelObject>() {
    @Override
    public void updateItem(MyModelObject item, boolean empty) {
        super.updateItem(item, empty);
        if (empty) {
            setText(null);
        } else {
            setText(getDisplayText(item));
        }
    }
};

// ...

private String getDisplayText(MyModelObject object) {
    // ...
    return ... ;
}

那么你只需要做

MyModelObject item = listView.getSelectionModel().getSelectedItem();
String displayText = getDisplayText(item);

(显然,如果您还没有设置单元工厂,则只需要listView.getSelectionModel().getSelectedItem().toString())

关于JavaFx ListView,获取列表中单元格的文本值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29697800/

相关文章:

java - 使用任务更新javafx UI而不使用Platform.RunLater

java - 使用 XQJ JSR 225 的 Xquery

android - 使用自定义 ArrayAdapter 在 ListView 中删除带有按钮的项目

Java:使用高版本 JDK 编译但在低版本 JRE 上运行时,防止使用高版本 API

c# - ListView 列标题液体大小?

html - 如何仅使用 html 和 css(不使用 Bootstrap )设计一个简单的 ListView (如 Android)

JavaFX 自定义 ScrollBar 在滚动时将事件传递给 TableView

java - Mac OSX 中用于 Intellij IDEA 的 JavaFX 场景生成器可执行文件在哪里?

java - 列出数据库中的表

java - Eclipse 内容辅助显示一些 javadoc,但不显示其他 javadoc