I have two variables inside a class: the amount and the maximum possible value for that amount.
I need a TableCell capable of receiving any number, as long as it doesn't surpass the maximum value present in each item. I also need both values for other stuff, such as implementing a custom StringConverter, a custom TextField, etc.
However, I can't access the item value inside setCellFactory() !!!
Here it is more or less what I have done:
public class Item {
private SimpleIntegerProperty amount;
private SimpleIntegerProperty max; // maximum
Item(int max,int amount){
this.max = new SimpleIntegerProperty(max);
this.amount = new SimpleIntegerProperty(amount);
}
public static TableView<Item> getTable(){
TableColumn<Item,Number> colAmnt = new TableColumn<Item, Number>("column");
colAmnt.setCellValueFactory(c -> c.getValue().amount); // I CAN access the item object (c.getValue()) here!
colAmnt.setCellFactory(d->{
// But I can't access it from here!!!
return new MaxNumberTableCell();
});
// unimportant stuff
colAmnt.setOnEditCommit((TableColumn.CellEditEvent<Item, Number> t) -> {
Item o = ((Item) t.getTableView().getItems().get(
t.getTablePosition().getRow()));
o.amount.setValue(t.getNewValue().intValue());
});
TableView<Item> t = new TableView<Item>();
t.getColumns().add(colAmnt);
t.setEditable(true);
return t;
}
public int getMax() {
return max.get();
}
}
I have tried to get the value by extending TableCell<S,T> class as shown below, but I receive NullPointerException.
class MaxNumberTableCell extends TableCell<Item,Number>{
public MaxNumberTableCell(){
super();
// Can't access from here either
int a = this.getTableRow().getItem().getMax(); // NullPointerException
// tldr: I need the value of a !
}
}
Edit: If you want a minimal work example, here is the Main
public class Main extends Application{
@Override
public void start(Stage stage) {
TableView<Item> t = Item.getTable();
ObservableList<Item> ol = FXCollections.observableArrayList();
ol.add(new Item(5,1));
t.setItems(ol);
Scene scene = new Scene(t);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}