Seems like a rarely asked question, so maybe extending GridPane is the wrong approach altogether. I did look at How to extend custom JavaFX components that use FXML and more.
I am trying to create a LawnGrid class that extends GridPane, the reason is to override the add() method to resize ImageView nodes as they are added. I also need to resize based on calculating the size of the LawnGrid and figuring out whether the lawn is wider than it is high, wanting to preserve an aspect ratio. I am leaving out details of implementation that seem irrelevant.
The problem is when I put a LawnGrid into the .fxml file it won't show in SceneBuilder (in IntelliJ) which I think is a symptom of what I am doing wrong. I get this error:
java.lang.NullPointerException / javafx.fxml.LoadException:
which points to my view.fxml: ... (inside a BorderPane)
<center>
<LawnGrid fx:id="lawnGridPane" style=" -fx-border-color:green; -fx-border-width: 10; -fx-border-style: solid;" BorderPane.alignment="CENTER">
</LawnGrid>
</center>
I want to add the constraints programmatically, maybe I need them up front but it seems like I would get a different error. Based on linked answer above, my LawnGrid.java starts with:
@DefaultProperty(value = "lawnGrid")
public class LawnGrid extends GridPane {
UPDATE: Based on Slaw's feedback I see the mistake of having the FXML annotation in the wrong place, moved it to my FXController.java:
// lawn representation for lawn display in GUI
@FXML
private LawnGrid lawnGridPane = new LawnGrid();
FWIW I also get a NPE when I try to run it, the application appears but gives NPE on a line where I refer to "this" inside LawnGrid. I assume I am missing something fundamental about how JavaFX instantiates objects and need to create the LawnGrid somewhere but I thought the .fxml file set this up.
EDIT: I did add super() to my constructors thinking that might make some difference but it didn't, I believe just by using extends
it calls super()? Here's the constructors in LawnGrid.java:
public LawnGrid(){
super();
// uses default max 10 rows 15 columns
setupLawnConstraints();
}
public LawnGrid(double rows, double columns){
super();
this.numRows = rows;
this.numCols = columns;
setupLawnConstraints();
}
public LawnGrid(double rows, double columns, DoubleProperty preferredSquareSizeProperty) {
super();
this.numRows = rows;
this.numCols = columns;
this.preferredSquareSizeProperty = preferredSquareSizeProperty;
}