You encounter an exception due to accessing the JavaFX UI from a separate thread. Here's how you can correctly implement threading:
Create a thread and start the database request on it:
Thread t = new Thread(new Runnable() { public void run() { requestCourseName(); } }, "Thread A"); t.start();
The javafx.concurrent API provides a convenient way to manage background threads and update the 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); } }
By implementing threading correctly, you ensure that long-running database requests do not block the UI thread, resulting in a responsive user interface.
The above is the detailed content of How to Properly Implement Threading for Database Requests in JavaFX to Avoid UI Blocking?. For more information, please follow other related articles on the PHP Chinese website!