Tuesday, April 3, 2018

JAVA, JAVAFX - listener and lambda expression

Since JDK 1.8 you can use lambda expression. This article compares old and new variants on one example with CheckBox listener.

Old variant (response for change in CheckBox):
@FXML CheckBox checkbox1;
@FXML Label label1;

@Override
public void initialize( URL url, ResourceBundle rb ) {               

  /* variant without lambda expression */
    
  checkbox1.selectedProperty().addListener( new ChangeListener< boolean >() {
    @Override
    public void changed( ObservableValue observable, Boolean oldValue, Boolean newValue ) {
      label1.setText( newValue.toString() );
    }
  } );        
        
  /* -- init */
    
  checkbox1.selectedProperty().set( true );    
}  
And new (optional - old variant is still working) with lambda expression:
@FXML CheckBox checkbox1;
@FXML Label label1;
  
@Override
public void initialize( URL url, ResourceBundle rb ) {               
   
  /* variant with lambda expression */
    
  checkbox1.selectedProperty().addListener(
    ( ObservableValue observable, Boolean oldValue, Boolean newValue ) -> {
      label1.setText( newValue.toString() );
      }
    );    
    
  /* -- init */
    
  checkbox1.selectedProperty().set( true );    
}  

Both variant have same result:

No comments:

Post a Comment