Saltar al contenido

Cómo agregar CheckBox a un TableView en JavaFX

Este enunciado ha sido evaluado por expertos así garantizamos la veracidad de nuestra esta noticia.

Solución:

Usos javafx.scene.control.cell.CheckBoxTableCell y el trabajo esta hecho!

  ObservableList< TableColumn< RSSReader, ? >> columns =
     _rssStreamsView.getColumns();
  [...]
  TableColumn< RSSReader, Boolean > loadedColumn = new TableColumn<>( "Loaded" );
  loadedColumn.setCellValueFactory(
    new Callback,ObservableValue>()
        @Override public
        ObservableValue call( CellDataFeatures p )
           return p.getValue().getCompleted(); );
  loadedColumn.setCellFactory(
     new Callback,TableCell>()
        @Override public
        TableCell call( TableColumn p )
           return new CheckBoxTableCell<>(); );
  [...]
  columns.add( loadedColumn );

ACTUALIZAR: mismo código usando expresiones lambda de Java 8

  ObservableList< TableColumn< RSSReader, ? >> columns =
     _rssStreamsView.getColumns();
  [...]
  TableColumn< RSSReader, Boolean > loadedColumn = new TableColumn<>( "Loaded" );
  loadedColumn.setCellValueFactory( f -> f.getValue().getCompleted());
  loadedColumn.setCellFactory( tc -> new CheckBoxTableCell<>());
  [...]
  columns.add( loadedColumn );

¡El recuento de líneas se divide por dos! (16 ==> 8)

ACTUALIZAR: mismo código usando la palabra contextual “var” de Java 10

  var columns = _rssStreamsView.getColumns();
  [...]
  var loadedColumn = new TableColumn( "Loaded" );
  loadedColumn.setCellValueFactory( f -> f.getValue().getCompleted());
  loadedColumn.setCellFactory( tc -> new CheckBoxTableCell<>());
  [...]
  columns.add( loadedColumn );

EDITAR para agregar un ejemplo editable funcional completo (Java 8)

public class Os 

   private final StringProperty  name   = new SimpleStringProperty();
   private final BooleanProperty delete = new SimpleBooleanProperty();

   public Os( String nm, boolean del ) 
      name  .set( nm  );
      delete.set( del );
   

   public StringProperty  nameProperty  ()  return name;   
   public BooleanProperty deleteProperty()  return delete; 


public class FxEditableCheckBox extends Application 

   @Override
   public void start( Stage stage ) throws Exception 
      final TableView view = new TableView<>();
      final ObservableList> columns = view.getColumns();

      final TableColumn nameColumn = new TableColumn<>( "Name" );
      nameColumn.setCellValueFactory( new PropertyValueFactory<>( "name" ));
      columns.add(  nameColumn );

      final TableColumn loadedColumn = new TableColumn<>( "Delete" );
      loadedColumn.setCellValueFactory( new PropertyValueFactory<>( "delete" ));
      loadedColumn.setCellFactory( tc -> new CheckBoxTableCell<>());
      columns.add( loadedColumn );

      final ObservableList items =
         FXCollections.observableArrayList(
            new Os( "Microsoft Windows 3.1"    , true  ),
            new Os( "Microsoft Windows 3.11"   , true  ),
            new Os( "Microsoft Windows 95"     , true  ),
            new Os( "Microsoft Windows NT 3.51", true  ),
            new Os( "Microsoft Windows NT 4"   , true  ),
            new Os( "Microsoft Windows 2000"   , true  ),
            new Os( "Microsoft Windows Vista"  , true  ),
            new Os( "Microsoft Windows Seven"  , false ),
            new Os( "Linux all versions :-)"   , false ));
      view.setItems( items );
      view.setEditable( true );

      final Button delBtn = new Button( "Delete" );
      delBtn.setMaxWidth( Double.MAX_VALUE );
      delBtn.setOnAction( e -> 
         final Set del = new HashSet<>();
         for( final Os os : view.getItems()) 
            if( os.deleteProperty().get()) 
               del.add( os );
            
         
         view.getItems().removeAll( del );
      );
      stage.setScene( new Scene( new BorderPane( view, null, null, delBtn, null )));
      BorderPane.setAlignment( delBtn, Pos.CENTER );
      stage.show();
   

   public static void main( String[] args ) 
      launch( args );
   

EDITAR para agregar un ejemplo editable funcional completo (Java 10)

public class Os 

   private final StringProperty  name   = new SimpleStringProperty();
   private final BooleanProperty delete = new SimpleBooleanProperty();

   public Os( String nm, boolean del ) 
      name  .set( nm  );
      delete.set( del );
   

   public StringProperty  nameProperty  ()  return name;   
   public BooleanProperty deleteProperty()  return delete; 


public class FxEditableCheckBoxJava10 extends Application 

   @Override
   public void start( Stage stage ) throws Exception 
      final var view       = new TableView();
      final var columns    = view.getColumns();
      final var nameColumn = new TableColumn( "Name" );
      nameColumn.setCellValueFactory( new PropertyValueFactory<>( "name" ));
      columns.add(  nameColumn );
      final var loadedColumn = new TableColumn( "Delete" );
      loadedColumn.setCellValueFactory( new PropertyValueFactory<>( "delete" ));
      loadedColumn.setCellFactory( tc -> new CheckBoxTableCell<>());
      columns.add( loadedColumn );
      final var items = FXCollections.observableArrayList(
         new Os( "Microsoft Windows 3.1"    , true  ),
         new Os( "Microsoft Windows 3.11"   , true  ),
         new Os( "Microsoft Windows 95"     , true  ),
         new Os( "Microsoft Windows NT 3.51", true  ),
         new Os( "Microsoft Windows NT 4"   , true  ),
         new Os( "Microsoft Windows 2000"   , true  ),
         new Os( "Microsoft Windows Vista"  , true  ),
         new Os( "Microsoft Windows Seven"  , false ),
         new Os( "Linux all versions :-)"   , false ));
      view.setItems( items );
      view.setEditable( true );
      final var delBtn = new Button( "Delete" );
      delBtn.setMaxWidth( Double.MAX_VALUE );
      delBtn.setOnAction( e -> 
         final var del = new HashSet();
         for( final var os : view.getItems()) 
            if( os.deleteProperty().get()) 
               del.add( os );
            
         
         view.getItems().removeAll( del );
      );
      stage.setScene( new Scene( new BorderPane( view, null, null, delBtn, null )));
      BorderPane.setAlignment( delBtn, Pos.CENTER );
      stage.show();
   

   public static void main( String[] args ) 
      launch( args );
   

Debe establecer un CellFactory en TableColumn.

Por ejemplo:

Callback, TableCell> booleanCellFactory = 
            new Callback, TableCell>() 
            @Override
                public TableCell call(TableColumn p) 
                    return new BooleanCell();
            
        ;
        active.setCellValueFactory(new PropertyValueFactory("active"));
        active.setCellFactory(booleanCellFactory);

class BooleanCell extends TableCell 
        private CheckBox checkBox;
        public BooleanCell() 
            checkBox = new CheckBox();
            checkBox.setDisable(true);
            checkBox.selectedProperty().addListener(new ChangeListener () 
                public void changed(ObservableValue observable, Boolean oldValue, Boolean newValue) 
                    if(isEditing())
                        commitEdit(newValue == null ? false : newValue);
                
            );
            this.setGraphic(checkBox);
            this.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
            this.setEditable(true);
        
        @Override
        public void startEdit() 
            super.startEdit();
            if (isEmpty()) 
                return;
            
            checkBox.setDisable(false);
            checkBox.requestFocus();
        
        @Override
        public void cancelEdit() 
            super.cancelEdit();
            checkBox.setDisable(true);
        
        public void commitEdit(Boolean value) 
            super.commitEdit(value);
            checkBox.setDisable(true);
        
        @Override
        public void updateItem(Boolean item, boolean empty) 
            super.updateItem(item, empty);
            if (!isEmpty()) 
                checkBox.setSelected(item);
            
        
    

TableColumn select = new TableColumn("CheckBox");
        select.setMinWidth(200);
        select.setCellValueFactory(new Callback, ObservableValue>() 

            @Override
            public ObservableValue call(
                    TableColumn.CellDataFeatures arg0) 
                Person user = arg0.getValue();

                CheckBox checkBox = new CheckBox();

                checkBox.selectedProperty().setValue(user.isSelected());



                checkBox.selectedProperty().addListener(new ChangeListener() 
                    public void changed(ObservableValue ov,
                            Boolean old_val, Boolean new_val) 

                        user.setSelected(new_val);

                    
                );

                return new SimpleObjectProperty(checkBox);

            

        );
        table.getColumns().addAll( select);

Reseñas y puntuaciones del post

Al final de la artículo puedes encontrar las críticas de otros desarrolladores, tú asimismo puedes mostrar el tuyo si te gusta.

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *