JavaFX:ObservableArrayList添加元素会冻结应用程序

时间:2018-10-11 13:30:50

标签: java javafx kotlin

在我的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()
    }
}

0 个答案:

没有答案