Search code examples
javajavafx-8fxml

How can i make custom event with property?


How can I make custom event and custom property with access to it from SceneBuilder/FXML? Should be available like this

this source gives the answer but only partially here

I need something like:

MyFragment.fxml

<SplitPane ......>
    <fx:script>
        function myFunction()
        {
            if(MyCustomControl.state){
                id0.setText('1111111')
            } else {
                id0.setText('2222222')
            }
        }
    </fx:script>
                           //How create this property? 
   <Label fx:id="id0" />   //           |              
                           //           V              
   <MyCustomControl        onMyCustomEvent="myFunction()"/>
</SplitPane>

Solution

  • For Kotlin:

    val MY_CUSTOM_EVENT =
        EventType<Event>(Event.ANY, "MY_CUSTOM_EVENT" + UUID.randomUUID().toString())
    var onOnlineClick = object : SimpleObjectProperty<EventHandler<Event>>() {
        override fun getBean(): Any {
            return this
        }
    
        override fun getName(): String {
            return "onMyCustomEvent"
        }
    
        override fun invalidated() {
            setEventHandler(MY_CUSTOM_EVENT, get())
        }
    }
    
    fun onMyCustomEvent(): ObjectPropertyBase<EventHandler<Event>> {
        return onMyCustomEvent
    }
    
    fun setOnMyCustomEvent(value: EventHandler<Event>) {
        onMyCustomEvent.set(value)
    }
    
    fun getOnMyCustomEvent(): EventHandler<Event> {
        return onMyCustomEvent.get()
    }
    

    Somewhere property

    fun myProperty(): BooleanProperty {
        return myCustomProperty ?: run {
            myCustomProperty = object : SimpleBooleanProperty(false) {
                override fun invalidated() {
                    fireEvent(Event(MY_CUSTOM_EVENT)) // <---this
                }
    
                override fun getBean(): Any {
                    return this
                }
    
                override fun getName(): String {
                    return "myProperty"
                }
            }
            return myCustomProperty as SimpleBooleanProperty
        }
    }