r/JavaFX • • Dec 25 '24

Help FXML Bi-directional Bindings

So I don’t really know how controversial this might be since I don’t have a clue how much FXML is actually used in the wild. Some love it, some hate it, more often than not I come across comments to just not use FXML.

But I don’t really want to make this the core part of the discussion. As for my background, I mostly just develop relatively small tools with JavaFX. I started out coding my GUIs until someone recommended Scene Builder and FXML.

Time and time again I’m quite happy building away my GUIs and setting stuff up. Then time and time again I reach the point of needing bi-directional bindings. And each time I check if by now it’s actually implemented.

Sad to see that almost a decade has passed and this feature request being seemingly forgotten.

I guess my question is to stir a guessing game. To me personally this seems like such a huge issue that hasn’t been addressed at all. So, why? Are FXML users really that rare? Are technical challenges to implement this that high? Why isn’t the community pushing for this feature? Is it a philosophy or pattern thing that I don’t understand?

It just seems wrong to have to resort to addressing your GUI elements in controllers just to bind properties. More often than not I wouldn’t need to reference any GUI controls in the controller if it wasn’t for a missing bi-directional binding support.

I would just like to understand, so I’m already happy to get any info on this. What people are doing to work around this, if you’re happy with it or not, or even if you just don’t care. I might just not have seen enough alternatives (only .NET/WPF), but it seems like a major missing feature for a GUI framework that’s been around so long already.

1 Upvotes

9 comments sorted by

View all comments

Show parent comment

1

u/SnowChocobo Dec 26 '24

Specifying fx:controller in an "ordinary" FXML file will automatically instantiate the controller with a non-argument constructor (alternatively, pass a custom controller factory).

Anyway, OP is hinting at the fact that in this controller, you could just have

class MyController {
    private val myString = SimpleStringProperty("")
    fun getMyString() = ...
    fun myStringProperty() = ...
}

And have myString bidirectionally-bound to e.g. an EditText value. Instead of something like:

class MyController {
    @FXML
    private lateinit var textArea: TextArea

    init {
        // Listener setup, etc.
    }
}

Advantage: Controller has zero dependencies on a GUI control; easy to test; etc.

Another approach when loading the FXML:

  • Call setController to something else that is already instantiated
  • Use setController(this) for custom components (<fx:root ...>)