Home > Database > Mysql Tutorial > How to Handle Threading Correctly in JavaFX Applications?

How to Handle Threading Correctly in JavaFX Applications?

Linda Hamilton
Release: 2024-12-20 19:19:19
Original
204 people have browsed it

How to Handle Threading Correctly in JavaFX Applications?

Understanding Threading in JavaFX

JavaFX imposes two essential rules for threading:

Rule 1 (GUI Threading):
Any interaction with a node in a JavaFX scene graph must occur on the JavaFX application thread. This thread is responsible for both rendering and handling user events.

Rule 2 (Background Threading):
Long-running operations should be executed on a background thread to prevent UI unresponsiveness.

Threading with javafx.concurrent API

JavaFX provides a Task class for managing background operations. Tasks have a call() method that executes on a separate thread. Once complete, tasks can update UI elements using their succeeded() and failed() event handlers. These handlers are invoked on the FX Application Thread, ensuring compliance with Rule 1.

Example: Database Access with Threading

Let's take your example of a database query and implement it using threading.

Data Access Object (DAO) Class:

public class CourseDAO {

    private Connection conn;

    public CourseDAO() throws Exception {
        // Establish database connection
    }

    public Course getCourseByCode(int code) throws SQLException {
        try (PreparedStatement stmt = conn.prepareStatement("SELECT * FROM course WHERE c_code = ?")) {
            stmt.setInt(1, code);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                // Create and populate a Course object
            } else {
                // Handle case where course doesn't exist
            }
        }
    }
}
Copy after login

Controller Class:

@FXML
private TextField courseId;
@FXML
private Label courseCodeLbl;

private CourseDAO courseDAO;

@FXML
public void getCourseOnClick() {
    final int courseCode = Integer.valueOf(courseId.getText());
    Task<Course> courseTask = new Task<>() {
        @Override
        protected Course call() throws Exception {
            return courseDAO.getCourseByCode(courseCode);
        }
    };

    courseTask.setOnSucceeded(e -> {
        Course course = courseTask.getValue();
        if (course != null) {
            courseCodeLbl.setText(course.getName());
        }
    });

    // Execute the task on a background thread
    exec.execute(courseTask);
}
Copy after login

In this example, the database query runs on a separate thread, adhering to Rule 2. After completion, the UI is updated on the FX Application Thread, complying with Rule 1.

The above is the detailed content of How to Handle Threading Correctly in JavaFX Applications?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template