JavaFX ChangeListener

0

JavaFX ChangeListener Tutorial:

JavaFX ChangeListener is notified if the value of the ObservableValue changes.

It only gets fired, if the value really changes.

Single ChangeListener can be used for many observableValue.

It gets old and new value.

ChangeListener is an interface it contains a method Changed() so we needs to implements it.

Changed() Method:

void changed(ObservableValue extends T> observable, T oldValue,T newValue){}

It is called when obesevableValue changed.

Register ChangeListener :

It added using addListener() method AS


myproperty.addListener(new ChangeListener(){
 
            @Override
            public void changed(ObservableValue observable, Object oldValue, Object newValue) {
                System.out.println(oldValue+" "+newValue);
            }
        });

Example of change listener:


package javafxtuts;


import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

/**
 *
 * @author JavaFXtuts.com
 */
public class Javafxtuts extends Application {
    
    @Override
    public void start(Stage primaryStage) {
       Label lb=new Label(" ");
        ComboBox ComboBox = new ComboBox();
        ComboBox.getItems().addAll("RAM","SHYAM","MANOJ","REKHA","PRAKASH");
        HBox root = new HBox();
        //to set the position of hbox(root) in center
        root.setAlignment(Pos.CENTER);
        root.getChildren().addAll(lb,ComboBox);
        ComboBox.valueProperty().addListener(new ChangeListener() {
        @Override 
        public void changed(ObservableValue ov, String s, String s1) {
            lb.setText(s1);
        }    

          
           
    });
        Scene scene = new Scene(root, 300, 250);
        
        primaryStage.setTitle("javafxtuts.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
}

Output:

Explanation:

we adding the changelistener and code inside the changed() method is used to set text of the label using setText() method as


ComboBox.valueProperty().addListener(new ChangeListener() {
        @Override 
        public void changed(ObservableValue ov, String s, String s1) {
            lb.setText(s1);
        }    
 });
 

And as you know s1 give the new selected(changed) value.

Share.

Leave A Reply