JavaFX Table Cell Editing
I case someone needs a working example, I was able to get the code to work with this tutorial by adding a
usernameCol.setCellFactory(
TextFieldTableCell.forTableColumn());
and changing the usernameCol.setOnEditCommit
to
usernameCol.setOnEditCommit(
(TableColumn.CellEditEvent<Account, String> t) ->
( t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setFieldUsername(t.getNewValue())
);
Here is the complete testController
class that should be working (Other files stayed the same)
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import java.net.URL;
import java.util.ResourceBundle;
public class testController implements Initializable {
@FXML
private TableColumn<Account, String> usernameCol;
@FXML
private TableColumn<Account, String> balanceCol;
@FXML
private TableView<Account> accountTable;
@FXML
private TableColumn<Account, String> bookieCol;
@FXML
private TableColumn<Account, String> passwordCol;
private ObservableList<Account> dataList =
FXCollections.observableArrayList(
new Account("bookie", "username", "password", "0"));
@Override
public void initialize(URL location, ResourceBundle resources) {
bookieCol.setCellValueFactory(
new PropertyValueFactory<>("fieldBookie"));
usernameCol.setCellValueFactory(
new PropertyValueFactory<>("fieldUsername"));
usernameCol.setCellFactory(
TextFieldTableCell.forTableColumn());
usernameCol.setOnEditCommit(
(TableColumn.CellEditEvent<Account, String> t) ->
( t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setFieldUsername(t.getNewValue())
);
passwordCol.setCellValueFactory(
new PropertyValueFactory<Account, String>("fieldPassword"));
balanceCol.setCellValueFactory(
new PropertyValueFactory<Account, String>("fieldBalance"));
accountTable.setItems(dataList);
}
}
I haven`t tried your example, but I think you just forgot to set the cellFactory for the specific column. Adding the folowing line should fix it:
usernameCol.setCellFactory(cellFactory);
You can add the textField to editing cell using :TextFieldTableCell.forTableColumn();
If you need comboBox try : ComboBoxTableCell.forTableColumn(list);
// TextField:
usernameCol.setCellFactory(TextFieldTableCell.forTableColumn());
// ComboBox:
ObservableList<String> list = FXCollections.observableArrayList();
list.add("name 1");
list.add("name 2");
list.add("name 3");
list.add("name 4");
Callback<TableColumn<Account, String>, TableCell<Account, String>> cbtc =
ComboBoxTableCell.forTableColumn(list);
usernameCol.setCellFactory(cbtc);