所以我在FXML中定义了一个列表视图
<ListView fx:id="editRecipeList" layoutX="14.0" layoutY="14.0"
onMouseClicked="#recipeEditListViewOnMouseClicked" prefHeight="406.0"
prefWidth="242.0" />
以及相应的方法
@FXML
protected void recipeEditListViewOnMouseClicked() {
System.out.println("method started");
List<Document> recipesForEditingClick = mongoDatabase.getCollection("recipes")
.find(eq("name", "somethng");
//etc
}
该方法不是很大,但第一行代码System.out.println()
5 秒后才执行!但是在同一程序的另一个列表视图中,列表视图没有速度问题吗?怎么可能?如果需要任何其他信息,请发表评论
如果对数据库的调用花费了相当长的时间,则需要将其放入后台线程中。在 JavaFX 中执行此操作的最佳方法是将调用封装在 Task
中。
尝试:
@FXML
protected void recipeEditListViewOnMouseClicked() {
System.out.println("method started");
editRecipeList.setDisable(true);
Task<List<Document>> getRecipesTask = new Task<List<Document>>() {
@Override
public List<Document> call() throws Exception {
return mongoDatabase.getCollection("recipes")
.find(eq("name", "somethng");
}
};
getRecipesTask.setOnSucceeded(e -> {
editRecipeList.setDisable(false);
List<Document> recipesForEditingClick = getRecipesTask.getValue();
// process results here...
//etc
});
Thread thread = new Thread(getRecipesTask);
thread.setDaemon(true);
thread.start();
}