2015-04-17 63 views
1

我想在JavaFx應用程序上顯示所選單元格的ListView中的文本。JavaFx ListView,獲取列表中的單元格的文本值

這樣做的目的是解決我在編寫應用程序時遇到的錯誤。當底層模型更改時,ListView中單元格的文本將無法正確更新。過去曾奏效。 我想寫一個黃瓜驗收測試,以便如果它再次發生,錯誤將被捕獲。

下面是這個特定場景的stepdefs。

@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,並找不到任何方法可以讓我得到單元格的文本。

+0

某處你必須設置在'ListView'電池工廠,以顯示比調用模型的'的toString()'方法的結果以外的東西。只需將該功能移出一個單獨的方法,然後調用它,傳遞模型對象(您只需使用listView.getSelectionModel()。getSelectedItem()')即可獲得該模型對象。 –

+0

我沒有使用細胞工廠。所以這不利於我。 – Awarua

+0

那麼單元格中顯示的值是多少? –

回答

1

如果您有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()

+0

不幸的是單元格中的文本沒有更新。但是,編輯字段時,模型會更新。我也沒有使用細胞工廠。 'listView.getSelectionModel()。getSelectedItem.toString()' 將調用鏈接到單元格的對象的toString方法。不是細胞本身的文字。 – Awarua

+0

你是什麼意思「我不使用細胞工廠」。如何以其他方式創建列表視圖中的單元格? –

+0

您可以使用ObservableList,他們被栓到ListView 你將不得不在控制器的初始化以下'listView.setItems(observableList);' 那麼你可以添加項目到observableList,他們將出現在ListView – Awarua

相關問題