JavaFX 2.0: What do I have to do to react on a row selection change in a table?

javafx-2

Solution

I think what you will want to do is add a ListChangeListener to the selected indices on the selection model of your TableView. It should go something like this...

tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); // just in case you didnt already set the selection model to multiple selection.
tableView.getSelectionModel().getSelectedIndices().addListener(new ListChangeListener<Integer>()
    {
        @Override
        public void onChanged(Change<? extends Integer> change)
        {
            if (change.getList().size() >= 2)
            {
                button.setDisable(false);
            }
            else
            {
                button.setDisable(true);
            }
        }

    });

I was originally going to suggest binding the disable property of the button to a selected indices property size on the table view being greater than 2, but there doesn't seem to be one provided. If you wanted to, you could create your own SimpleIntegerProperty and update it inside of the list change listener, binding the disable property of the button to the value of your SimpleIntegerProperty being greater than 2. I hope this answer is helpful!

Problem

I want to do a very easy and common thing but don't find a way to do it with JavaFX. I have a TableView with two columns and want to enable a button if at least one row is selected. If no row is selected I want to disable the button again. For that I need to get a selection changed event or something like that. Shouldn't be there a possibility to set the selectionModel of the tableView on action or add a listener to it? What do I have to do?

Original source