0
votes

I am new to JavaFX and I built a tableview in JavaFX, and here is the example code:

TableView<Person> table = new TableView<>();
table.setEditable(true);
final TableColumn<Person, String>nameCol = new TableColumn<>("Name");
nameCol.setCellValueFactory(new PropertyValueFactory<>("name"));

After I adding a list into the table, everything works just fine.
But when I add these code after the NameCol:

nameCol.setCellFactory(param -> new XCell());

public class XCell extends TableCell<Person, String> {
    @Override
    protected void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);
        setStyle(empty ? null : "-fx-font-weight: bold; -fx-alignment: center");
//...
    }
}

Then, the data from nameColumn went missing. But when I comment that code:

//nameCol.setCellFactory(param -> new XCell());

All the data just went back again. It is so wired that I can't find out what is wrong with that.

I'll appreciate if anyone could explain what is happened and fix it.

1

1 Answers

0
votes

The problem is you @Override the TableCell's updateItem method which handles the stuff about what and how is displayed in the cell. If you extending the TableCell you have to take care about displaying graphic or text in the cell.

So you should do something like this:

public class XCell extends TableCell<TestApp.Person, String> {
    @Override
    protected void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);
        if(empty){  // check if the cell contains an item or not, if it not you want an empty cell without text.
            setText(null);
        }else {
            setText(item);
            setStyle("-fx-font-weight: bold; -fx-alignment: center"); // You can do the styling here.
            // Any further operations to this cell can be done here in else, since here you have the data displayed.
        }
        // Since as I see you don't have any graphics in the cell(like TextField, ComboBox,...) you 
        // don't have to take care about the graphic, but only the displaying of the text.
    }
}