由于从单独的线程访问 JavaFX UI,您遇到了异常。以下是正确实现线程的方法:
创建一个线程并在其上启动数据库请求:
Thread t = new Thread(new Runnable() { public void run() { requestCourseName(); } }, "Thread A"); t.start();
javafx.concurrent API 提供了一种便捷的管理方式后台线程并更新 UI。
// DAO encapsulates database access public class WidgetDAO { public List<Widget> getWidgetsByType(String type) { ... } } // Controller handles UI operations public class MyController { private WidgetDAO widgetAccessor; private Executor exec; public void searchWidgets() { String searchString = widgetTypeSearchField.getText(); Task<List<Widget>> widgetSearchTask = new Task<>() { @Override protected List<Widget> call() throws Exception { return widgetAccessor.getWidgetsByType(searchString); } }; widgetSearchTask.setOnSucceeded(e -> widgetTable.getItems().setAll(widgetSearchTask.getValue())); exec.execute(widgetSearchTask); } }
// DAO encapsulates database access public class MyDAO { public Course getCourseByCode(int code) { ... } } // Controller handles UI operations public class MyController { private MyDAO myDAO; private Executor exec; public void searchCourse() { int courseCode = Integer.valueOf(courseId.getText()); Task<Course> courseTask = new Task<>() { @Override protected Course call() throws Exception { return myDAO.getCourseByCode(courseCode); } }; courseTask.setOnSucceeded(e -> { Course course = courseTask.getValue(); courseCodeLbl.setText(course.getName()); }); exec.execute(courseTask); } }
通过正确实现线程,可以确保长时间运行的数据库请求不会阻塞 UI 线程,产生响应式用户界面。
以上是如何在 JavaFX 中正确实现数据库请求的线程以避免 UI 阻塞?的详细内容。更多信息请关注PHP中文网其他相关文章!