Tuesday, March 20, 2018

JAVAFX - How make "raw" object centering in the form (with properties binding)

public class FXMLMainController implements Initializable {
  
  @FXML private Label lbl1;
  
  @Override
  public void initialize( URL url, ResourceBundle rb ) {               
  }  
  
  /* Method for label centering */

  public void prepare() {
    Scene scene = lbl1.getScene();       
  
    if ( scene != null ) {
      lbl1.layoutXProperty().bind( scene.widthProperty().subtract( 
        lbl1.layoutBoundsProperty().get().getWidth()).divide( 2 ) );
      
      lbl1.layoutYProperty().bind( scene.heightProperty().subtract( 
        lbl1.layoutBoundsProperty().get().getHeight()).divide( 2 ) );
    }
    
  }
}
Method prepare() must be called after creating Scene class instance:
@Override
    public void start(Stage stage) throws Exception {

        FXMLLoader fLoader = new FXMLLoader( getClass().getResource( "FXMLMain.fxml" ) );
        Parent root = fLoader.load();
        FXMLMainController controller = fLoader.< fxmlmaincontroller >getController();      
        
        Scene scene = new Scene(root);
        
        stage.setScene(scene);
        stage.show();

        /* needs to be called here */
        controller.prepare();
    }
Output:

No comments:

Post a Comment