[英]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.