Wednesday, August 13, 2014

Add listener to StringProperty to monitor property change

Example to implement ChangeListener() to monitor StringProperty change.



package javafx_propertylistener;

import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_PropertyListener extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        
        StringProperty stringProperty = new SimpleStringProperty();
        
        TextField textInput = new TextField();
        Label labelOutput1 = new Label();
        Label labelObservable = new Label();
        Label labelOldvalue = new Label();
        Label labelNewvalue = new Label();
        
        labelOutput1.textProperty().bind(textInput.textProperty());
        
        Button btn = new Button();
        btn.setText("Updated");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            
            @Override
            public void handle(ActionEvent event) {
                stringProperty.set(textInput.getText());
            }
        });
        
        // add listener for stringProperty
        // to be called when stringProperty changed
        stringProperty.addListener(new ChangeListener(){

            @Override
            public void changed(ObservableValue observable, Object oldValue, Object newValue) {
                labelObservable.setText((String)observable.getValue());
                labelOldvalue.setText((String)oldValue);
                labelNewvalue.setText((String)newValue);
            }
        });
        
        VBox vBox = new VBox();
        vBox.getChildren().addAll(textInput, labelOutput1, btn, 
            labelObservable, labelOldvalue, labelNewvalue);
        
        StackPane root = new StackPane();
        root.getChildren().add(vBox);
        
        Scene scene = new Scene(root, 300, 250);
        
        primaryStage.setTitle("Java-Buddy");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
    
}

No comments:

Post a Comment