简体   繁体   中英

editable listview in javafx

I've got a list definition in fxml

<ListView fx:id="select_values" editable="true" prefHeight="200.0" prefWidth="200.0" />

My controller class for the list looks like this

public class ScriptGeneratorController implements Initializable {
    @FXML
    private ListView<String> select_values;
    private List<String> selectValueList = new ArrayList<>(Arrays.asList("", "", "", "", "", "", ""));
    private ListProperty<String> selectValueListProperty = new SimpleListProperty<>();

    @FXML
    private void handleQuestionGenerationAction(ActionEvent event) {
        System.out.println(selectValueList); // list of [,,,,,]
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        select_values.itemsProperty().bind(selectValueListProperty);
        select_values.setCellFactory(TextFieldListCell.forListView());
        select_values.setOnEditCommit(event -> select_values.getItems().set(event.getIndex(), event.getNewValue()));
        selectValueListProperty.set(FXCollections.observableArrayList(selectValueList));
    }
}

But when I click on the button to do the action where I print list to console I get the list of empty strings (the same as initial). But on my form I clearly populate the values

在此处输入图片说明

What's the problem?

The documentation for FXCollections.observableArrayList(...) says it

Creates a new observable array list and adds a content of collection col to it.

So your code creates a new list which is used as the backing list for the list view, and copies the content of selectValueList to that new list. When the user edits the content, the backing list is changed, but the changes are not propagated back to selectValueList .

You seem to have too many layers of data here. Probably all you need is

public class ScriptGeneratorController implements Initializable {
    @FXML
    private ListView<String> select_values;
    private ObservableList<String> selectValueList = FXCollections.observableArrayList("", "", "", "", "", "", "");

    @FXML
    private void handleQuestionGenerationAction(ActionEvent event) {
        System.out.println(selectValueList); 
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        select_values.setItems(selectValueList);
        select_values.setCellFactory(TextFieldListCell.forListView());
    }
}

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