How to extend custom JavaFX components that use FXML

前端 未结 2 1504
遥遥无期
遥遥无期 2021-01-04 13:09

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

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-04 13:10

    From what I understand, you want to be able to extend existing components and avoid copy & pasting the entire markup for the new component.

    You can define an extension point for the component with the @DefaultProperty annotation. Look at e.x. javafx.scene.layout.Pane: There is a ObservableList getChildren() defined with @DefaultProperty("children"). In this way, when you use e.x an HBox (extends Pane) as the root element for your component, all child components are added to the children property defined by the Pane.

    In the same way you can define extension points in FXML:

    SpecializedButton.fxml (I simplified it a little for this example)

    
      
        
    
      
        

    The HBox fx:id="extension" will be my extension point:

    @DefaultProperty(value = "extension")
    public class SpecializedButton extends HBox
    {
        @FXML private HBox extension;
    
        public ObservableList getExtension() {
            return extension.getChildren();
        }
        // ... more component specific code
    }
    

    SuperSpecializedButton.fxml

    
      
    

    And:

    public class SuperSpecializedButton extends SpecializedButton
    {
        // ... more component specific code
    }
    

    As you can see, I need only to define fxml for the super-specialized component.

    This code will work only on JavaFX >= 2.1. Beforehand the component injection for the super class didn't worked with the FXMLLoader.

    I added an working example on github: https://github.com/matrak/javafx-extend-fxml

提交回复
热议问题