Skip to content
Advertisement

Bind StringProperty to Label from a Singleton

I have a singleton called MenuText. It is responsible for displaying the correct text in the menu. It gets updated dynamically.

JavaScript

I have a fxml file, but the MenuText can’t have a reference to it. (This would contradict the MVVM architectural style)

JavaScript

Initially I used <fx:define> to setup a reference to the MenuText from the fxml file, but this doesn’t allow private constructors. It shouldn’t be that difficult, because MenuText is static, but I’m unable to make a static reference to it’s singleton.

I tried <Button text="${MenuText.getInstance().text}">


Update

As mentioned in this answer, I shouldn’t use the Singleton Pattern. Based on this I added an ApplicationFactory:

JavaScript

Is this the correct approach? I now have a MenuFactory, which gets also created in the JavaFX start() method. It sets the parent of the scene.

JavaScript

The start() mehtod looks like this:

JavaScript

This makes it way more complicated and I’m not sure if this is correct. Furthermore, I still don’t know how I set the MenuText in the fxml file. I tried, but I think this isn’t the correct way to set a namespace in fxml.

JavaScript

I read these documentations but don’t understand how I can set this custom namespace.

Advertisement

Answer

Be aware that the singleton pattern is widely considered to be an anti-pattern. However, if you really want to do this:

Initially I used <fx:define> to setup a reference to the MenuText from the fxml file

This is the correct approach. You can combine it with fx:factory to get a reference to an instance of a class that does not have a (public) default constructor:

JavaScript

And then do

JavaScript

Another solution is to “manually” insert the MenuText instance into the FXML namespace:

JavaScript

And then

JavaScript

should work with no additional FXML code. This approach allows you to avoid using the singleton pattern (you’re basically injecting the dependency into the FXML, so you could combine it easily with a DI framework).

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement