Skip to content

Instantly share code, notes, and snippets.

@UrsKR
Created June 8, 2012 13:51
Show Gist options
  • Save UrsKR/2895713 to your computer and use it in GitHub Desktop.
Save UrsKR/2895713 to your computer and use it in GitHub Desktop.
JavaFX 2's TableView creates more rows than required
import com.sun.javafx.collections.ObservableListWrapper;
import javafx.application.Application;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
import javafx.util.Callback;
import java.util.Collections;
import java.util.List;
public class TableDemo extends Application {
private int rowIndex = 0;
private int elementIndex = 0;
public static void main(String[] args) {
System.out.println("Rows and Elements start counting at 0.");
System.out.println();
launch(args);
}
@Override
public void start(Stage stage) {
FlowPane pane = new FlowPane();
final TableView tableView = new TableView();
tableView.setRowFactory(new CountingRowFactory());
tableView.getColumns().add(createColumn());
pane.getChildren().add(tableView);
List items = Collections.singletonList(new Object());
tableView.setItems(new ObservableListWrapper(items));
stage.setScene(new Scene(pane));
stage.show();
}
private TableColumn createColumn() {
TableColumn column = new TableColumn("Column");
column.setCellFactory(new PrintingCellFactory());
column.setCellValueFactory(new CountingValueFactory());
return column;
}
private static class PrintingCellFactory implements Callback {
@Override
public Object call(Object column) {
return new TableCell() {
@Override
protected void updateItem(Object o, boolean b) {
super.updateItem(o, b);
if (tableRowProperty().isNotNull().get()) {
System.out.print("Row ");
System.out.print(getTableRow().getUserData());
System.out.print(": Element ");
System.out.println(o);
}
setText(String.valueOf(o));
}
};
}
}
private class CountingRowFactory implements Callback {
@Override
public Object call(Object o) {
TableRow row = new TableRow();
row.setUserData(rowIndex);
rowIndex++;
return row;
}
}
private class CountingValueFactory implements Callback {
@Override
public Object call(Object o) {
SimpleIntegerProperty property = new SimpleIntegerProperty(elementIndex);
elementIndex++;
return property;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment