2015-04-17 59 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

相关问题