我正在尝试获取 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/