Javafx 8 Tableview selection with checkbox

前端 未结 2 537
迷失自我
迷失自我 2021-01-03 13:15

I\'ve set up a multiselection enabled tableview and am trying to attach a listener a checkbox inserted into a column to the selection model of the table.

che         


        
2条回答
  •  [愿得一人]
    2021-01-03 13:37

    Ok, so this one way to do it. You'll need a BooleanProperty in your backing model to hold the value of the check box so that the table will 'remember' if that rows check box should be selected or not if the row scrolls out of view and then back again.

    TableColumn  checkCol = new TableColumn<>("Check");
    checkCol.setCellValueFactory( new PropertyValueFactory( "checkBoxValue" ) );
    checkCol.setCellFactory( new Callback, TableCell>()
    {
        @Override
        public TableCell call( TableColumn param )
        {
            return new CheckBoxTableCell()
            {
                {
                    setAlignment( Pos.CENTER );
                }
                @Override
                public void updateItem( Boolean item, boolean empty )
                {
                    if ( ! empty )
                    {
                        TableRow  row = getTableRow();
    
                        if ( row != null )
                        {
                            int rowNo = row.getIndex();
                            TableViewSelectionModel  sm = getTableView().getSelectionModel();
    
                            if ( item )  sm.select( rowNo );
                            else  sm.clearSelection( rowNo );
                        }
                    }
    
                    super.updateItem( item, empty );
                }
            };
        }
    } );
    checkCol.setEditable( true );
    checkCol.setMaxWidth( 50 );
    checkCol.setMinWidth( 50 );
    

提交回复
热议问题