Handling nested Properties in JavaFX / TornadoFX - kotlin

I want to have a window which shows info about certain ViewModel
Suppose you have a simple Person:
class Person(name: String) {
val nameProperty = SimpleStringProperty(name)
}
and have instance of Person save in property:
val personProperty = SimpleObjectProperty(Person("John"))
what's the correct solution to show Person's name in label?
Using this:
label(personProperty.value.nameProperty)
Will not update when I update the property's person:
personProperty.value = Person("Joe")
(That's obvious because only the reference changes, not the value itself)
So is there any good way to do this or do I have to manually add listeners for personProperty and update which Person does label point to?
EDIT:
I also found this question: JavaFX binding and property change, but it doesn't contain anything new and useful that I didn't know about, is there any TornadoFX-specific way of doing this?

This is exactly what the ItemViewModel does for you. If you want to make a binding for the name property that updates automatically, outside of an ItemViewModel, you can use the TornadoFX feature select:
val nameProperty = personProperty.select { it.nameProperty }

A listener can be attached to the property:
personProperty.onChange {
it?.nameProperty.let(nameLabel.textProperty().bind)
}
This can be wrapped in extension function to simplify the task.

Related

Tornadofx - Keeping globally accessed properties in a ViewModel?

Reasoning:
Hello guys. I'm building an evolution simulator as personal project. I have a few parameters set on textfields, such as the speed of the simulation and the number of "organisms". These are going to be accessed by multiple components of the application. Because i would also like to use validation on a few parameters, I set up a ViewModel like such:
class ParametersModel: ViewModel() {
// These properties would likely be DoubleProperty, but for simplicity lets pretend they are strings
val simulationSpeed = bind { SimpleStringProperty() }
val organismsGenerated = bind { SimpleStringProperty() }
}
... and then perform the validation tests on the textfields:
val model = ParametersModel()
textfield(model.simulationSpeed).required()
This works alright, but the issue with it is that I'm defining the model properties as a bind to an empty SimpleDoubleProperty, which is redundant since I'm never commiting this model (the program should always read changes as they are typed). At the same time, I cant define the model properties as simply:
class ParametersModel: ViewModel() {
val simulationSpeed = SimpleStringProperty()
val organismsGenerated = SimpleStringProperty()
}
Because I then get an error about the validation:
The addValidator extension can only be used on inputs that are already bound bidirectionally to a property in a Viewmodel. Use validator.addValidator() instead or make the property's bean field point to a ViewModel.
The other option I could take would be to make a class named something like GlobalProperties, which would keep my properties and also a ValidationContext. I could then add validators by using validationContext.addValidator and pass the textfields. But at this point I feel I'm just coding a ViewModel equivalent.
Question:
Is ViewModel the correct way of keeping "globally" accessed parameters set by textfields? If so, is there a way to not have to set the model properties as a bind of an empty one, since i dont ever need to commit anything?
Usually you would use a ViewModel with some sort of model. Then you can use the ViewModel to handle user input, which stores the current state of the user input, and the backing model will only be update when the ViewModel is committed, assuming validation passes (which seems at odds with your claim that you "dont ever need to commit anything").
Something like this:
class Parameters {
val simulationSpeedProperty = SimpleStringProperty(...)
var simulationSpeed by simulationSpeedProperty
val organismsGeneratedProperty = SimpleStringProperty(...)
var organismsGenerated by organismsGeneratedProperty
}
class ParametersModel(parameters: Parameters): ItemViewModel<Parameters>(parameters) {
val simulationSpeed = bind(Parameters::simulationSpeedProperty)
val organismsGenerated = bind(Parameters::organismsGeneratedProperty)
}
Then you can be sure that the Parameters backing the ParametersModel always has valid values in it (assuming of course it was initialized with valid values).

Trying to use ViewModels inside of another ViewModel, Errors with LifecycleObserver and Ownership (Kotlin)

Im trying to get some data out of other ViewModels inside another ViewModel to make my code smaller, but im having a problem trying to implement what already worked on a fragment or in a activity, this is what i got:
class ObraConMediaViewModel(private val context: ViewModelStoreOwner,
private val id: Int): ViewModel(), LifecycleObserver {
var allObras: LiveData<ArrayList<ObraConMedia>>
private lateinit var viewModelobras: ViewModelObras
private lateinit var viewModelMediaObra: ViewModelMediaObra
val repositoryobras =ObrasRepository()
val repositoryMediaObra = MediaObraRepository()
val viewModelFactoryobras = ViewModelFactoryObras(repositoryobras)
val viewModelMediaObraFactory = ViewModelMedIaObraFactory(repositoryMediaObra)
init{
viewModelobras = ViewModelProvider(context, viewModelFactoryobras)
.get(ViewModelObras::class.java) // requireActivity() when called
viewModelMediaObra = ViewModelProvider(context, viewModelMediaObraFactory)
.get(ViewModelMediaObra::class.java)
viewModelobras.getObras(id)
viewModelobras.myResponse.observe(this , Observer { response ->
if (response.isSuccessful){
Log.d("Response", response.body()?.ans?.get(0)?.autor)
Log.d("Response", response.body()?.ans?.get(1)?.autor)
}else{
Log.d("Response", response.errorBody().toString())
}})
viewModelMediaObra.getMediaObra(Constantes.PRUEBA_ID)
viewModelMediaObra.myResponse.observe(this, Observer { response ->
if (response.isSuccessful){
Log.d("Response", response.body()?.ans?.get(0)?.filePath)
}
})
}}
I was having trouble with the Observer but extending the class to LifecycleObserver fixed it, i have no idea if this will even work but the only error that i have right now its the owner of the .observe(this,....), i dont seem to find a way to pass a lifecycleowner from the fragment to this viewmodel. All the variables i need to make this viewmodel work are inside those two responses. If this is a very bad way to do it please tell me. Thanks for reading.
Kindly note that above approach is not correct.
One should not create a instance of ViewModel inside another ViewModel.
There is a possibility that one ViewModel may get destroyed before another. This will lead to garbage reference and memory leaks.
I would recommend you to create the instance of both View Models in an Activity/Fragment and then call respective methods of ViewModel from Activity/Fragment.
Also, as you want to make your code smaller and concise, I highly recommend you Shared ViewModel.
This Shared ViewModel can be used by two fragments.
Please refer to this link

Why are variables declared after root automatically added to UI in TornadoFx?

I have stumbled upon a behaviour in TornadoFx that doesn't seem to be mentioned anywhere (I have searched a lot) and that I'm wondering about.
If I define a view like this with the TornadoFx builders for the labels:
class ExampleView: View() {
override
val root = vbox{ label("first label") }
val secondLabel = label("second label")
}
The result is:
That is, the mere definition of secondLabel automatically adds it to the rootof the scene.
However, if I place this definition BEFORE the definition of root...
class ExampleView: View() {
val secondLabel = Label("second label")
override
val root = vbox{ label("first label") }
}
... or if I use the JavaFx Labelclass instead of the TornadoFx builder ...
class ExampleView: View() {
override
val root = vbox{ label("first label") }
val secondLabel = Label("second label")
}
... then it works as I expect:
Of course, I can simply define all variables in the view before I define the rootelement but I'm still curious why this behaviour exists; perhaps I am missing some general design rule or setting.
The builders in TornadoFX automatically attach themselves to the current parent in the scope they are called in. Therefore, if you call a builder function on the View itself, the generated ui component is automatically added to the root of that View. That's what you're seeing.
If you really have a valid use case for creating a ui component outside of the hierarchy it should be housed in, you shouldn't call a builder function, but instead instantiate the element with it's constructor, like you did with Label(). However, the use cases for such behavior are slim to none.
Best practice is to store value properties in the view or a view model and bind the property to the ui element using the builders. You then manipulate the value property when needed, and the change will automatically update in the ui. Therefore, you very very seldom have a need to access a specific ui element at a later stage. Example:
val myProperty = SimpleStringProperty("Hello world")
override val root = hbox {
label(myProperty)
}
When you want to change the label value, you just update the property. (The property should be in an injected view model in a real world application).
If you really need to have a reference to the ui element, you should declare the ui property first, then assign to it when you actually build the ui element. Define the ui property using the singleAssign() delegate to make sure you only assign to it once.
var myLabel: Label by singleAssign()
override val root = hbox {
label("My label) {
myLabel = this
}
}
I want to stress again that this is very rarely needed, and if you feel you need it you should look to restructure your ui code to be more data driven.
Another technique to avoid storing references to ui elements is to leverage the EventBus to listen for events. There are plenty of examples of this out there.

Please Explain Property Delegates

I am trying to learn Kotlin and TornadoFX. One thing I keep seeing is code like this:
val TextProperty = SimpleStringProperty()
var text by Textproperty
I've been reading up on the documentation
https://edvin.gitbooks.io/tornadofx-guide/content/part2/Property%20Delegates.html
so I've "absorbed" that they are useful for when values in a model change, but I need further help really grasping the concept. Something doesn't quite seem to be clicking. Does anyone have any examples, videos, etc. that demonstrate the purpose and usefulness of these property delegates?
The important point here is that JavaFX requires or at least prefers observable properties. Instead of declaring a mutable property, you would declare one of the JavaFX property types, depending on what property type you want (String, Double, Int etc). All you really need is to declare this property:
class Customer {
val ageProperty = SimpleIntegerProperty()
}
You can get by with just this, without using any delegates. However, if you want to mutate this property, you need to change the value property inside the property you defined, so the code looks like this:
customer.ageProperty.value = 42
This is cumbersome, so to make it simple, you'd want to add getters and setters. Doing this manually would look something like this:
val ageProperty = SimpleIntegerProperty()
var age: Int
get() = ageProperty.value
set(value) { ageProperty.value = value }
Now you can set the age of a Customer like this:
customer.age = 42
This is much more convenient, but you'd have to declare all that code for each property, so in TornadoFX we introduced property delegates that takes care of all that with a simple statement, so:
val ageProperty = SimpleIntegerProperty()
var age by ageProperty
The end result is the same, without you having to do any of the heavy lifting.
Just to be clear, this explains the property delegates, not why JavaFX properties are useful. JavaFX properties allow you to bind to a UI element, like a text field for example. Changes to the text field will be written back into the property, and changes to the property would be written back to the UI.
Once you can written something like
class C { var text by Textproperty }
all c.text = blabla will be compiled to TextProperty.setValue(c, ::text, blabla), and c.text will be compiled to TextProperty.getValue(c, ::text). This enables the library (the provider of TextProperty) to take over the operations on text.
Ref: https://kotlinlang.org/docs/reference/delegated-properties.html

Create an arbitrary view

So, I have a case in which I need to have N rows in form of: Label TextView/Checkbox. Maybe I will have to have more than those two views, so I want to be able to support anything that is TornadoFx View.
I've created an interface that has one method that returns TornadoFx View and it looks like this:
interface ValueContainer {
fun getView() : View
}
One of the implementations looks like this:
class BooleanValueContainer(val checked: Boolean) : ValueContainer {
val valueProperty = SimpleBooleanProperty(checked)
override fun getView(): View {
return (object : View() {
override val root = checkbox {
bind(valueProperty)
}
})
}
}
Now, when I try to use it inside init block, it doesn't show in the layout. root is GridPane and parameters is a list of objects that have name and reference to ValueContainer implementation (BooleanValueContainer or other one which I haven't shown):
init {
with(root) {
parameters.map {
row(it.name) {
it.parameterContainer.getView()
}
}
}
}
I'm stuck here for quite a while and I've tried anything I could find but nothing really worked except putting textview or checkbox block instead of getView() call, but then I would have to have logic on what view should I show inside this class which represents a view and I don't want that.
The reason this is not working for you is that you simply call parameterContainer.getView() but you don't add the View to the row. I think what's confusing you is that for builders you can just say label() for example, and it's added to the current Node in the builder tree. In your case, you just say Label() (just create an instance of Label, not call the label builder), which would create a new Label, but not add it to the children list of the current Node. To solve your problem, do:
this += it.parameterContainer.getView()
This will add the View to the row.
Apart from this, I don't quite see the point of the ValueContainer. What does it solve to put a View inside this container object? I suspect this as well might be due to a misunderstanding and I'd like to understand why you feel that you need this construct.