Controlling JavaFX GUI from Other Methods?

113 views Asked by At

Basically, I'm creating a program that syncs HUE lights, and I'm having trouble incorporating the Listener that detects when the light bridge has been connected with my JavaFX GUI; I want it to switch a Label from "Not Connected" to "Connected" whenever the listener detects that it has connected.

Here's some pseudocode of how the program is structured.

public class MainClass extends Application {

boolean connected;
Label label;

public static void main(){
    launch(args);                       //Neccesary to start JavaFX
}

public static void start(){
    ConnectToHueLights();               //Takes abt 30s to connect to bridge
    Label label = “Searching for connection”;       //Message while connecting
    Window.addLabel();                  //Adds label to hue lights
    Window.show();                  //Makes window visible
}

private HueLightsListener(){
    //Once connected, can do whatever inside of a void method inside of this Listener
    private void onConnectionResponds(){
        label = “Connected”
        connected = true;
    }
}

public void ConnectToHueLights(){
    create new Listener();
}

Basically, the label doesn't change whenever the listener is active, and I'm not sure how to do that.

Thanks!

1

There are 1 answers

0
trashgod On

Use a suitable Worker to establish the connection to the bridge. Choose Task for a single unit of work; choose Service to manage multiple tasks. Use the task's updateMessage() method to notify the worker's message property listeners. You can pass a reference to the update method to your HueLightsListener, as shown here.

HueLightsListener listener = new HueLightsListener(this::updateMessage);

Your implementation of onConnectionResponds() can then tell the reference to accept() messages as needed.

public void onConnectionResponds() {
    updater.accept("Connected");
    …
}

As an aside, your implementation of call(), which runs in the background, can periodically poll the connection, while checking isCancelled(), and then send more commands once connected.