Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a listener to a variable in Java/JavaFX which gets called on variable change

I know that there are listeners in JavaFX, and i'm sure Java. But I'm confused as how to implement them.

I have a boolean variable that is changed throughout my program. Everytime the boolean is changed, I want a function myFunc() to be ran.

Can this be done easily?

like image 987
CREW Avatar asked Apr 01 '12 23:04

CREW


2 Answers

As simple as this:

public void changeBooleanFlag(boolean bEnabled)
{
    if(booleanFlag == bEnabled) return;
    booleanFlag = bEnabled;
    myFunc();
}

and whenever you want to change the boolean flag, you should do it via this method.

like image 40
Eng.Fouad Avatar answered Sep 23 '22 09:09

Eng.Fouad


If you are using JavaFX 2 then it provides an out-of-box solutions for both JavaBeans component architecture and Observer design pattern. Moreover it gives a great flexibility of associating the state of variables by the property bindings. The code below illustrates the property changed events and the binding of property variables. Of course you can wrap the property accessors to hide details by like getFlag() and setFlag() below, and use them in the rest of application.

public class Demo extends Application {

    private BooleanProperty booleanProperty = new SimpleBooleanProperty(true);

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

    @Override
    public void start(Stage primaryStage) {

        // Add change listener
        booleanProperty.addListener(new ChangeListener<Boolean>() {

            @Override
            public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
                System.out.println("changed " + oldValue + "->" + newValue);
                myFunc();
            }
        });

        Button btn = new Button();
        btn.setText("Toggle boolean flag");
        btn.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                booleanProperty.set(!booleanProperty.get()); //toggle
                System.out.println("toggled to " + booleanProperty.get());
            }
        });

        // Bind to another property variable
        btn.underlineProperty().bind(booleanProperty);

        StackPane root = new StackPane();
        root.getChildren().add(btn);
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();
    }

    public boolean getFlag() {
        return booleanProperty.get();
    }

    public void setFlag(boolean val) {
        booleanProperty.set(val);
    }
}
like image 89
Uluk Biy Avatar answered Sep 24 '22 09:09

Uluk Biy