javafxtableviewjavafx-8selectionmodel

Set SelectionModel for TableView in FXML


I want to set the SelectionModel of the TableView from the FXML, but I can not find how to do this. I already tried the following:

1.Just set it as a property of the TableView:

<TableView selectionModel="MULTIPLE">

2.Set the property the same as the ListView works (see: https://community.oracle.com/thread/2315611?start=0&tstart=0):

<TableView multiSelect="true">

3.Set the property in a different way:

<TableView>
    <selectionModel>
        <TableView fx:constant="MULTIPLE" />
    </selectionModel>
</TableView>

4.Another version:

<TableView>
    <selectionModel>
        <SelectionModel fx:constant="MULTIPLE" />
    </selectionModel>
</TableView>

5.Selection model (different):

<TableView>
    <selectionModel>
        <SelectionModel selectionModel="MULTIPLE" />
    </selectionModel>
</TableView>

None of this works.

Any help is greatly appreciated!


Solution

  • Should it be possible on FXML this should be the way:

    <TableView fx:id="table" prefHeight="200.0" prefWidth="200.0" >
        <columns>
          <TableColumn prefWidth="75.0" text="C1" />
        </columns>
        <selectionModel>
            <SelectionMode fx:constant="MULTIPLE"/>
        </selectionModel>
    </TableView>
    

    Unfortunately, when you run it you get an exception:

    java.lang.IllegalArgumentException: Unable to coerce SINGLE to class javafx.scene.control.TableView$TableViewSelectionModel.
    at com.sun.javafx.fxml.BeanAdapter.coerce(BeanAdapter.java:495)
    

    This is happening because the bean adapter tries reflexively to find in the class javafx.scene.control.TableView$TableViewSelectionModel the valueOf of javafx.scene.control.SelectionMode.MULTIPLE, but it doesn't find it.

    There's an unresolved JIRA ticket for this here.

    The only working solution I've found, based on that report, is using scripting capabilities:

    ...
    <?language javascript?>
    
        <TableView fx:id="table" prefHeight="200.0" prefWidth="200.0" >
            <columns >
              <TableColumn fx:id="col" prefWidth="75.0" text="C1" />
            </columns>
        </TableView>
        <fx:script>          
              table.getSelectionModel().setSelectionMode(javafx.scene.control.SelectionMode.MULTIPLE);
        </fx:script> 
    

    Which is the same as doing it by code...