Johan Rovala
Johan Rovala

Reputation: 174

JavaFX bind buttons to eachother

Not to sure if my title question is correct.

What I'm trying to achieve is to have one button create a Vehicle object. Then have a different button call the method embark (which will just update some fields).

So in general:

One button to create an instance of the object Vehicle. A second button to call a method on this instance.

        btnCar.setOnAction(new EventHandler<ActionEvent>(){
        public void handle(ActionEvent event){
            Vehicle C = new Car(amountPass, "hej", "hej");
        }
    });
    btnEmbark.setOnAction(new EventHandler<ActionEvent>(){
        public void handle(ActionEvent event){
            ferry.embark(C);
        }
    });

Thanks!

Upvotes: 0

Views: 203

Answers (1)

eckig
eckig

Reputation: 11134

There are several ways to that, the first that comes to my mind is with JavaFX properties:

ObjectProperty<Object> object = new SimpleObjectProperty<>();

Button button1 = new Button("create");
button1.setOnAction(ev -> object.set(new Object()));

Button button2 = new Button("magic");
button2.setOnAction(ev -> object.get().hashCode());
button2.disableProperty().bind(Bindings.isNull(object));

With Bindings we ensure that the second button can only be fired when the custom object has already been created and stored.

Another way would be to write a subclass of Button doing the communication with another Button. That is a matter of personal taste.

Upvotes: 2

Related Questions