How do I properly extend a custom JavaFX component to add or modify its GUI components if it uses FXML for the view?
As an example scenario, suppose I use the follow
I haven't done that before, but you could implement the Initializable interface to setup the view component when you instantiate a new custom component.
To add new component(labels, buttons, img, etc...) I would wrap all the children component on the view file, within an AnchorPane, GridPane, VBox or the one you prefer to add more components programmatically. Since you are extending your class from HBox you could do this already.
Here's what I would do:
public class SpecializedButton extends HBox implements Initializable{
@FXML private Button button;
@FXML private Label label;
public SpecializedButton(){
FXMLLoader loader = new FXMLLoader( getClass().getResource( "SpecializedButton.fxml" ) );
loader.setRoot( this );
loader.setController( this );
try {
loader.load();
} catch ( IOException e ) {
throw new RuntimeException( e );
}
}
// specialized methods for this specialized button
// ...
public void doSomething() {
button.setText( "Did something!" );
}
@Override
public void initialize(URL url, ResourceBundle rb) {
button.setText("Initialized Text");
}
}
So for the HighlySpecializedButton class:
public class HighlySpecializedButton extends SpecializedButton {
public HighlySpecializedButton (){
super();
}
// HighlySpecializedButton methods
@Override
public void initialize(URL url, ResourceBundle rb) {
this.getChildren().add(new Button("New Button"));
}
}
Hope this could help you