[英]JavaFx ListView, getting the text value of a cell in the list
我试图在ListView中获取所选单元格的文本,因为它显示在JavaFx应用程序上。
这样做的目的是修复编写应用程序时遇到的错误。 当基础模型更改时,ListView中单元格的文本将无法正确更新。 过去一直有效。 我正在尝试编写黄瓜验收测试,以便再次发生该错误时,可以将其捕获。
以下是此特定方案的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()
需要listView.getSelectionModel().getSelectedItem().toString()
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.