在我的JavaFX应用程序中,我尝试设置choicebox
项(大约90个字符串项),如下所示:
private fun initChoiceBox(choiceBox: ChoiceBox<String>, elements: List<String>) {
val detectLabel = "Detect language"
choiceBox.items = FXCollections.observableArrayList(detectLabel)
choiceBox.selectionModel.selectFirst()
choiceBox.items.addAll(elements) // hanging is here
}
上面的方法是从javafx.concurrent.Task
#onSucceeded调用的:
private fun initializeSelectLanguage() {
val task = GetSupportedLanguagesTask()
task.onSucceeded = EventHandler { _ ->
val value = task.value
val elements = value.langs.map { it.value } // around 90 elements in my case
initChoiceBox(selectLanguage, elements)
initChoiceBox(translationLanguage, elements)
}
task.onFailed = EventHandler {
println(it.source.message) // todo
}
executor.submit(task)
}
如何解决这种冻结?如果要插入视图的项目过多,该如何更新视图?
更新1
我这样创建ChoiceBoxes
(使用fxml
个文件):
<HBox>
<StackPane>
<ChoiceBox fx:id="selectLanguage"/>
</StackPane>
</HBox>
StackPane
文件的根fxml
指向控制器类,如下所示:
fx:controller="com.pany.view.Controller"
并且控制器初始化类似于此示例:
class Controller : Initializable, Disposeable {
@FXML
private lateinit var selectLanguage: ChoiceBox<String>
@FXML
lateinit var translationLanguage: ChoiceBox<String>
private val executor = Executors.newFixedThreadPool(1)
override fun initialize(location: URL?, resources: ResourceBundle?) {
initializeSelectLanguage() // method is already posted above
}
override fun dispose() {
executor.shutdownNow()
}
}