简体   繁体   中英

JavaFx ListView, getting the text value of a cell in the list

I am trying to get the text of the selected cell in a ListView as it is displayed on a JavaFx application.

The purpose of this is to fix a bug I encountered when writing an application. The text of the cells in the ListView would not update properly when the underlying model changed. Which has worked in the past. I am trying to write a cucumber acceptance test, so that if it occurs again the bug will be caught.

Below is the stepdefs for this particular scenario.

@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));
}

I have looked through the ListView JavaDoc and could not find any methods that can get me the text of the cell.

If you have a ListView , then either the text displayed in the cell is the result of calling toString() on the model object, or you have set a cell factory on the ListView . In the latter case, just refactor the logic to get the display text into a separate method:

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 ... ;
}

Then you just need to do

MyModelObject item = listView.getSelectionModel().getSelectedItem();
String displayText = getDisplayText(item);

(And obviously, if you haven't set a cell factory, you just need listView.getSelectionModel().getSelectedItem().toString() )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM