Search code examples
javajavafxfxml

How to create custom composite control without FXML?


I'd like to create class that represents composite control. This will be HBox that contains other controls like TextFields etc.

I know that it can be done with use of FXML like in this tutorial, but I want to do it without it.

This is my approach to solve this problem:

Class of composite control

public class VInputText extends HBox {

    private HBox hbox;
    private FontAwesomeIconView icon;
    private TextField textField;
    private Label label;

    public VInputText(double spacing) {

        hbox = new HBox(spacing);
        hbox.setAlignment(Pos.CENTER_LEFT);
        hbox.setPrefSize(Control.USE_COMPUTED_SIZE, Control.USE_COMPUTED_SIZE);

        icon = new FontAwesomeIconView();
        icon.setGlyphName("TIMES");
        icon.setSize("1.3em");

        textField = new TextField();

        label = new Label("<- my validated field");

        hbox.getChildren().addAll(icon, textField, label);
    }
}

FXML

<AnchorPane prefHeight="300.0" prefWidth="400.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="pl.edu.utp.wtie.controllers.AppController">
   <children>
      <VBox fx:id="vBox" prefHeight="300.0" prefWidth="400.0" spacing="5.0" />
   </children>
</AnchorPane>

Controller

public class AppController {

    @FXML
    private VBox vBox;

    @FXML
    void initialize() {
        System.out.println("AppController.java");

        VInputText input = new VInputText(5);

        vBox.getChildren().add(input);

    }
}

The problem is that app is compiling but composite control doesn't show on the scene. If remaining code will be necessary then I can paste it. Thanks in advance.


Solution

  • I'm pasting solution solved by someone, but answer was deleted. Instead of creating HBox it should be used this keyword:

    public class VInputText extends HBox {
    
        private FontAwesomeIconView icon;
        private TextField textField;
        private Label label;
    
        public VInputText(double spacing) {
    
            this.setSpacing(spacing);
            this.setAlignment(Pos.CENTER_LEFT);
            this.setPrefSize(Control.USE_COMPUTED_SIZE, Control.USE_COMPUTED_SIZE);
    
            icon = new FontAwesomeIconView();
            icon.setGlyphName("TIMES");
            icon.setSize("1.3em");
    
            textField = new TextField();
    
            label = new Label("<- my validated field");
    
            this.getChildren().addAll(icon, textField, label);
        }
    }