All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.dankito.utils.javafx.ui.controls.AutoCompletionSearchTextField.kt Maven / Gradle / Ivy

package net.dankito.utils.javafx.ui.controls

import javafx.beans.value.ObservableValue
import javafx.event.EventTarget
import javafx.scene.control.ContextMenu
import javafx.scene.control.TextField
import tornadofx.ListCellFragment
import tornadofx.bind
import tornadofx.opcr
import kotlin.reflect.KClass


fun  EventTarget.autocompletionsearchtextfield(value: String? = null, op: AutoCompletionSearchTextField.() -> Unit = {}) =
        opcr(this, AutoCompletionSearchTextField().apply { if (value != null) text = value }, op)

fun  EventTarget.autocompletionsearchtextfield(property: ObservableValue, op: AutoCompletionSearchTextField.() -> Unit = {}): AutoCompletionSearchTextField
        = autocompletionsearchtextfield().apply {
    bind(property)
    op(this)
}



class AutoCompletionSearchTextField : TextField() {

    var onAutoCompletion: ((T) -> Unit)? = null

    var getContextMenuForItemListener: ((item: T) -> ContextMenu?)?
        get() { return autoCompletionBinding.getContextMenuForItemListener }
        set(value) { autoCompletionBinding.getContextMenuForItemListener = value }


    var listCellFragment: KClass>?
        get() { return autoCompletionBinding.listCellFragment }
        set(value) { autoCompletionBinding.listCellFragment = value }


    private var autoCompletionBinding = AutoCompletionBinding(this)


    init {
        autoCompletionBinding.setOnAutoCompleted { e -> onAutoCompletion?.invoke(e.completion) }

        autoCompletionBinding.prefWidthProperty().bind(widthProperty())

        var previousY = 0.0

        boundsInParentProperty().addListener { _, _, newValue ->
            if(newValue.minY != previousY) {
                previousY = newValue.minY

                updateSuggestionsListPosition()
            }
        }
    }


    fun setAutoCompleteList(autoCompletionList: Collection, queryToSelectFromAutoCompletionList: String = text) {
        autoCompletionBinding.setAutoCompleteList(autoCompletionList, queryToSelectFromAutoCompletionList)
    }

    private fun updateSuggestionsListPosition() {
        autoCompletionBinding.updatePopupPosition()
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy