由於從單獨的執行緒存取 JavaFX UI,您遇到了例外。以下是正確實作執行緒的方法:
建立一個執行緒並在其上啟動資料庫請求:
Thread t = new Thread(new Runnable() { public void run() { requestCourseName(); } }, "Thread A"); t.start();
// 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); } }使用WidgetDAO 和任務的範例
// 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); } }使用MyDAO 和任務的範例透過正確實作線程,可以確保長時間運行的資料庫請求不會阻塞UI 線程,產生響應式使用者介面。
以上是如何在 JavaFX 中正確實作資料庫請求的執行緒以避免 UI 阻塞?的詳細內容。更多資訊請關注PHP中文網其他相關文章!