简体   繁体   中英

JavaFX: how to access UI thread components from other class

I am new to JavaFX and I am trying to do following:

I have main class with UI, important part being

public class Main extends Application {

    ...

    scene = new Scene(new Group()); 

    final Label label = new Label("Device name");
    label.setFont(new Font("Arial", 20));
    label.setId("label");

    DeviceConnector connector = new DeviceConnector(scene);
}

In class in other file I have some chained threads. Last of them if each successful (they connect to bluetooth) reads device name. This is what I want to display on the label from above.

Unfortunately I have not found any other (rather ellegant) solution than this:

public class DeviceConnector {

    Scene mScene;

    public DeviceConnector(Scene scene) {

        mScene = scene;
    }

    private void ReadDeviceName {

        this.deviceName = device.GetName();

        Platform.runLater(new Runnable() {

            @Override
            public void run() {

                Label label = (Label) mScene.lookup("#label");
                label.setText(deviceName);
            }
        });
    }
}

Is there any proper way to access components in JavaFX GUI (something like Mediator pattern)?

Thank you.

Most elements in JavaFX own an observable property, which represents the value. In the case of a label, its a textProperty() , which you can fetch and edit. All edits to that StringProperty (which is the type, returned by the textProperty() method), will be displayed in the related label.

See http://docs.oracle.com/javafx/2/api/javafx/scene/control/Labeled.html#textProperty%28%29

I suggest the approach to fetch the StringProperty, handle it as a model in a MVC structure and store it in a globally reachable model repository. In your logic thread, fetch the device name and write the result into the model aka StringProperty, and your label will be notified by the change and display the fetched value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM