建立在David的解决方案之上:
我添加了UP按键功能,还添加了ESC按键功能以隐藏弹出窗口。除此之外,您可以在构造AutoSuggestor对象时指定回调函数,当从列表中选择建议时将调用该函数。
import javax.swing.border.LineBorder
import java.util.ArrayList
import javax.swing.event.DocumentListener
import java.awt.*
import java.awt.event.*
import javax.swing.*
import javax.swing.event.DocumentEvent
/**
* Author of the original version: David @ https://stackoverflow.com/users/1133011/david-kroukamp
*/
class Test {
init {
val frame = JFrame()
frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
val f = JTextField(10)
val autoSuggestor = object : AutoSuggestor(f, frame, ArrayList(), Color.WHITE.brighter(), Color.BLUE, Color.RED, 0.75f) {
override fun wordTyped(typedWord: String?): Boolean {
//create list for dictionary this in your case might be done via calling a method which queries db and returns results as arraylist
val words = ArrayList()
words.add("hello")
words.add("heritage")
words.add("happiness")
words.add("goodbye")
words.add("cruel")
words.add("car")
words.add("war")
words.add("will")
words.add("world")
words.add("wall")
setDictionary(words)
//addToDictionary("bye");//adds a single word
return super.wordTyped(typedWord)//now call super to check for any matches against newest dictionary
}
}
val p = JPanel()
p.add(f)
frame.add(p)
frame.pack()
frame.isVisible = true
}
companion object {
@JvmStatic
fun main(args: Array) {
SwingUtilities.invokeLater { Test() }
}
}
}
internal open class AutoSuggestor(val textField: JTextField, val container: Window, words: ArrayList, popUpBackground: Color, private val suggestionsTextColor: Color, private val suggestionFocusedColor: Color, opacity: Float, private val callback: (String) -> Unit = {}) {
private val suggestionsPanel: JPanel
val autoSuggestionPopUpWindow: JWindow
private var typedWord: String? = null
private val dictionary = ArrayList()
private var currentIndexOfSpace: Int = 0
private var tW: Int = 0
private var tH: Int = 0
private val documentListener = object : DocumentListener {
override fun insertUpdate(de: DocumentEvent) {
checkForAndShowSuggestions()
}
override fun removeUpdate(de: DocumentEvent) {
checkForAndShowSuggestions()
}
override fun changedUpdate(de: DocumentEvent) {
checkForAndShowSuggestions()
}
}
val addedSuggestionLabels: ArrayList
get() {
val sls = ArrayList()
for (i in 0 until suggestionsPanel.componentCount) {
if (suggestionsPanel.getComponent(i) is SuggestionLabel) {
val sl = suggestionsPanel.getComponent(i) as SuggestionLabel
sls.add(sl)
}
}
return sls