0

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.

blizzard
  • 99
  • 8
  • What is your question? What is the main issue you have with your sample code? I guess if you are using FXML, you could use some of the techniques from: [Passing Parameters JavaFX FXML](http://stackoverflow.com/questions/14187963/passing-parameters-javafx-fxml). For multi-threading, you will either need Platform.runLater or to use [Tasks and Services](http://docs.oracle.com/javafx/2/threads/jfxpub-threads.htm), there are numerous samples of different usage patterns in the [Task](http://docs.oracle.com/javase/8/javafx/api/javafx/concurrent/Task.html) and Service javadoc. – jewelsea Aug 05 '14 at 04:40

1 Answers1

2

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.

Korashen
  • 2,144
  • 2
  • 18
  • 28
  • thank you for an answer, this is similar to my Mediator idea. i am gonna implement it but with "bind"s, hope it will be as good as listeners – blizzard Aug 05 '14 at 06:05