How to add CheckBox's to a TableView in JavaFX

2019-01-10 15:33发布

In my Java Desktop Application I have a TableView in which I want to have a column with CheckBoxes.

I did find where this has been done http://www.jonathangiles.net/javafx/2.0/CellFactories/ but as the download is not available and because I don't know how soon Jonathan Giles will answer my email I thought I'd ask...

How do I put a CheckBox in a cell of my TableView?

12条回答
萌系小妹纸
2楼-- · 2019-01-10 15:43

Uses javafx.scene.control.cell.CheckBoxTableCell<S,T> and the work's done !

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

UPDATE: same code using Java 8 lambda expressions

  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 );

Lines count is divided by two! (16 ==> 8)

UPDATE: same code using Java 10 "var" contextual word

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

EDIT to add full functional editable example (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<Os> view = new TableView<>();
      final ObservableList<TableColumn<Os, ?>> columns = view.getColumns();

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

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

      final ObservableList<Os> 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<Os> 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 );
   }
}

EDIT to add full functional editable example (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<Os>();
      final var columns    = view.getColumns();
      final var nameColumn = new TableColumn<Os, Boolean>( "Name" );
      nameColumn.setCellValueFactory( new PropertyValueFactory<>( "name" ));
      columns.add(  nameColumn );
      final var loadedColumn = new TableColumn<Os, Boolean>( "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<Os>();
         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 );
   }
}
查看更多
聊天终结者
3楼-- · 2019-01-10 15:47

The simplest solution is probably to do it in FXML:

  1. First create the class below:

    public class CheckBoxCellFactory<S, T>
              implements Callback<TableColumn<S, T>, TableCell<S, T>> {
        @Override public TableCell<S, T> call(TableColumn<S, T> p) {
            return new CheckBoxTableCell<>();
        }
    }
    
  2. Then include a cell factory in your FXML:

    <TableColumn text="Select" fx:id="selectColumn" >
        <cellFactory>
            <CheckBoxCellFactory/>
        </cellFactory>
    </TableColumn>
    

You also need to add an import in the FXML, such as <?import com.assylias.factories.*?>


Bonus: you can make the factory more customisable, for example to determine where the checkbox should appear, by adding fields to the CheckBoxCellFactory class, such as:

private Pos alignment = Pos.CENTER;
public Pos getAlignment() { return alignment; }
public void setAlignment(Pos alignment) { this.alignment = alignment; }

And the FXML:

<cellFactory>
    <CheckBoxCellFactory alignment="BOTTOM_RIGHT"/>
</cellFactory>
查看更多
干净又极端
4楼-- · 2019-01-10 15:50

This is the way is do it

tbcSingleton.setCellValueFactory(data -> data.getValue().singletonProperty());
tbcSingleton.setCellFactory( param -> {
    return new TableCell<FXMLController, Boolean>(){
        {
            setAlignment(Pos.CENTER);
        }
        protected void updateItem(Boolean item, boolean empty){
            if(!empty && item!=null) {
                CheckBox cb = new CheckBox();
                cb.setSelected(item);
                cb.setFocusTraversable(false);
                cb.selectedProperty().addListener((obs,old,niu)->listaFXMLController.get(getIndex()).setSingleton(niu));
                setGraphic(cb);
            }else
                setGraphic(null);
        }
    };
});
  • cb.setFocusTraversable(false) is necesary to prevent focus getting stuck on it.

  • setGraphic(null) is necesary to erase anything left behind after deleting an item or whenever the source list changes

  • cb.selectedProperty().addListener((obs,old,niu)->(your stuff...)); this is where you catch the new value of the CheckBox and do whatever you want with it.

Heres another one with a ToggleGroup and ToggleButtons

tbcTipoControlador.setCellValueFactory(data -> data.getValue().controllerTypeProperty());
tbcTipoControlador.setCellFactory( param -> {
    return new TableCell<FXMLController, ControllerType>() {
        {
            setAlignment(Pos.CENTER);
        }
        protected void updateItem(ControllerType item, boolean empty){
            if(!empty && item!=null) {
                ToggleButton tbModal = new ToggleButton("Modal");
                tbModal.selectedProperty().addListener((obs,old,niu)->{
                    if(niu)
                        listaFXMLController.get(getIndex()).setControllerType(ControllerType.MODAL);
                });
                tbModal.setSelected(item.equals(ControllerType.MODAL));
                ToggleButton tbPlain = new ToggleButton("Plain");
                tbPlain.selectedProperty().addListener((obs,old,niu)->{
                    if(niu)
                        listaFXMLController.get(getIndex()).setControllerType(ControllerType.PLAIN);
                });
                tbPlain.setSelected(item.equals(ControllerType.PLAIN));
                ToggleButton tbApplication= new ToggleButton("Application");
                tbApplication.selectedProperty().addListener((obs,old,niu)->{
                    if(niu)
                        listaFXMLController.get(getIndex()).setControllerType(ControllerType.APPLICATION);
                });
                tbApplication.setSelected(item.equals(ControllerType.APPLICATION));
                ToggleGroup gp = new ToggleGroup();
                tbModal.setFocusTraversable(false);
                tbPlain.setFocusTraversable(false);
                tbApplication.setFocusTraversable(false);
                tbModal.setPrefWidth(120);
                tbPlain.setPrefWidth(120);
                tbApplication.setPrefWidth(120);
                gp.getToggles().addAll(tbModal,tbPlain,tbApplication);
                HBox hb = new HBox();
                hb.setAlignment(Pos.CENTER);
                hb.getChildren().addAll(tbModal,tbPlain,tbApplication);
                setGraphic(hb);
            }else
                setGraphic(null);
        }
    };
});

I did some test and memory consumption is basically the same as using a ComboBoxTableCell

This is how my little application looks (sry, my main language is Spanish and i build it for personal use) enter image description here

查看更多
聊天终结者
5楼-- · 2019-01-10 15:52

for me, works with this solution:

Callback<TableColumn, TableCell> checkboxCellFactory = new Callback<TableColumn, TableCell>() {

        @Override
        public TableCell call(TableColumn p) {
            return new CheckboxCell();
        }
    };
    TableColumn selectColumn = (TableColumn) tbvDatos.getColumns().get(1);
    selectColumn.setCellValueFactory(new PropertyValueFactory("selected"));
    selectColumn.setCellFactory(checkboxCellFactory);

and the tableCell:

public class CheckboxCell extends TableCell<RowData, Boolean> {
CheckBox checkbox;

@Override
protected void updateItem(Boolean arg0, boolean arg1) {
    super.updateItem(arg0, arg1);
        paintCell();
}

private void paintCell() {
    if (checkbox == null) {
        checkbox = new CheckBox();
        checkbox.selectedProperty().addListener(new ChangeListener<Boolean>() {

            @Override
            public void changed(ObservableValue<? extends Boolean> ov,
                    Boolean old_val, Boolean new_val) {
                setItem(new_val);
                ((RowData)getTableView().getItems().get(getTableRow().getIndex())).setSelected(new_val);
            }
        });
    }
    checkbox.setSelected(getValue());
    setText(null);
    setGraphic(checkbox);
}

private Boolean getValue() {
    return getItem() == null ? false : getItem();
}
}

if you dont need to make the checkbox with edit event

查看更多
可以哭但决不认输i
6楼-- · 2019-01-10 15:53

There is a very simple way of doing this, you don't need to modify your model class with SimpleBooleanProperty or whatever, just follow these steps:

1 - Suppose you have a "Person" object with a isUnemployed method:

public class Person {
    private String name;
    private Boolean unemployed;

    public String getName(){return this.name;}
    public void setName(String name){this.name = name;}
    public Boolean isUnemployed(){return this.unemployed;}
    public void setUnemployed(Boolean unemployed){this.unemployed = unemployed;}
}

2 - Create the callback class

import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;

public class PersonUnemployedValueFactory implements Callback<TableColumn.CellDataFeatures<Person, CheckBox>, ObservableValue<CheckBox>> {
    @Override
    public ObservableValue<CheckBox> call(TableColumn.CellDataFeatures<Person, CheckBox> param) {
        Person person = param.getValue();
        CheckBox checkBox = new CheckBox();
        checkBox.selectedProperty().setValue(person.isUnemployed());
        checkBox.selectedProperty().addListener((ov, old_val, new_val) -> {
            person.setUnemployed(new_val);
        });
        return new SimpleObjectProperty<>(checkBox);
    }
}

3 - Bind the callback to the table column

If you use FXML, put the callback class inside your column:

<TableView fx:id="personList" prefHeight="200.0" prefWidth="200.0">
    <columns>
        <TableColumn prefWidth="196.0" text="Unemployed">
            <cellValueFactory>
                <PersonUnemployedValueFactory/> <!--This is how the magic happens-->
            </cellValueFactory>
        </TableColumn>

        ...
    </columns>
</TableView>

Don't forget to import the class in your FXML:

<?import org.yourcompany.yourapp.util.PersonUnemployedValueFactory?>

Without FXML, do it like this:

TableColumn<Person, CheckBox> column = (TableColumn<Person, CheckBox>) personTable.getColumns().get(0);
column.setCellValueFactory(new PersonUnemployedValueFactory());

4 - That's it

Everything should work as expected, with the value being set to the backing bean when you click on the checkbox, and the checkbox value correctly being set when you load the items list in your table.

查看更多
放我归山
7楼-- · 2019-01-10 15:53

Inspired from the previous answers, this is the shortest possible version, I think.

checkBoxColumn.setCellValueFactory(c -> {
    c.getValue().booleanProperty().addListener((ch, o, n) -> {
    // do something
    });
    return c.getValue().booleanProperty();
});
checkBoxColumn.setCellFactory(CheckBoxTableCell.forTableColumn(checkBoxColumn));
查看更多
登录 后发表回答