Last active
December 11, 2019 08:44
-
-
Save aymen083/9c605e1b22ed36e0e48c5f46ac925948 to your computer and use it in GitHub Desktop.
Make an Javafx ComoboBox completable coded in kotlin based on http://stackoverflow.com/questions/19924852/autocomplete-combobox-in-javafx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.demo.app | |
import javafx.collections.ObservableList | |
import javafx.event.EventHandler | |
import javafx.scene.control.ComboBox | |
import javafx.scene.input.KeyCode | |
import javafx.scene.input.KeyEvent | |
fun <T> ComboBox<T>.makeAutocompletable() = AutoCompleteComboBoxExtension<T>(this) | |
/** | |
* Created by anouira on 15/02/2017. | |
*/ | |
class AutoCompleteComboBoxExtension<T>(val comboBox : ComboBox<T> ) : EventHandler<KeyEvent> { | |
private var data: ObservableList<T>? = comboBox.items | |
private var moveCaretToPos = false | |
private var caretPos: Int = 0 | |
init { | |
with(this.comboBox) { | |
isEditable = true | |
onKeyPressed = EventHandler<KeyEvent> { hide() } | |
onKeyReleased = this@AutoCompleteComboBoxExtension | |
} | |
} | |
override fun handle(event: KeyEvent?) { | |
val code = event?.code | |
val isControlDown = event?.isControlDown ?: false | |
val isShiftDown = event?.isShiftDown ?: false | |
val text = comboBox.editor.text | |
val caretPosition = comboBox.editor.caretPosition | |
if(isControlDown) { | |
when (code) { | |
KeyCode.V -> "" | |
else -> return | |
} | |
} | |
if(isShiftDown) { | |
when (code) { | |
KeyCode.LEFT,KeyCode.RIGHT,KeyCode.HOME,KeyCode.END -> return | |
else -> "" | |
} | |
} | |
when (code) { | |
KeyCode.DOWN, KeyCode.UP -> { | |
if (!comboBox.isShowing) { | |
comboBox.show() | |
} else { | |
caretPos = -1 | |
moveCaret(text.length) | |
} | |
return | |
} | |
KeyCode.BACK_SPACE, KeyCode.DELETE -> { | |
moveCaretToPos = true | |
caretPos = comboBox.editor.caretPosition | |
} | |
KeyCode.RIGHT, KeyCode.LEFT, KeyCode.HOME, KeyCode.END, KeyCode.TAB, KeyCode.SHIFT, KeyCode.CONTROL -> return | |
else -> "" | |
} | |
val list = data?.filtered { it.toString().toLowerCase().contains(text.toLowerCase()) } | |
comboBox.items = list | |
comboBox.editor.text = text | |
if (!moveCaretToPos) { | |
caretPos = -1 | |
} | |
moveCaret(caretPosition) | |
if (!(list?.isEmpty() ?: true)) { | |
comboBox.show() | |
} | |
} | |
private fun moveCaret(textLength: Int) { | |
if (caretPos == -1) { | |
comboBox.editor.positionCaret(textLength) | |
} else { | |
comboBox.editor.positionCaret(caretPos) | |
} | |
moveCaretToPos = false | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment