Showing posts with label javafx - properties. Show all posts
Showing posts with label javafx - properties. Show all posts

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:

Monday, January 15, 2018

JAVAFX - How bind controls by properties

Suppose this .fxml form:











Add this code to form controller initialize() method:
public class FXMLMainController implements Initializable {  
  @FXML private ChoiceBox< javafx.geometry.side > choiceBox;
  @FXML private TabPane tabPane;
  
  @Override
  public void initialize( URL url, ResourceBundle rb ) {
    choiceBox.getItems().addAll( javafx.geometry.Side.values() );        
    choiceBox.setValue( Side.TOP );
    
    tabPane.sideProperty().bind( choiceBox.valueProperty() );
  }  
  
}

How you can see, tabPane.side property is binded to choicebox.value - so, after change in choicebox.value is immediately changed tabPane.side.