Using threads to make database requests

后端 未结 3 568
挽巷
挽巷 2020-11-22 00:39

I\'m trying to understand how threads works in java. This is a simple database request that returns a ResultSet. I\'m using JavaFx.

    package application;
         


        
3条回答
  •  忘了有多久
    2020-11-22 01:12

    Exception in thread "Thread A" java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread A

    The exception is trying to tell you that you are trying to access JavaFX scene graph outside the JavaFX application thread. But where ??

    courseCodeLbl.setText(rs.getString(1)); // <--- The culprit
    

    If I can't do this how do I use a background thread?

    The are different approaches which leads to similar solutions.

    Wrap you Scene graph element with Platform.runLater

    There easier and most simple way is to wrap the above line in Plaform.runLater, such that it gets executed on JavaFX Application thread.

    Platform.runLater(() -> courseCodeLbl.setText(rs.getString(1)));
    

    Use Task

    The better approach to go with these scenarios is to use Task, which has specialized methods to send back updates. In the following example, I am using updateMessage to update the message. This property is bind to courseCodeLbl textProperty.

    Task task = new Task() {
        @Override
        public Void call() {
            String courseName = "";
            Course c = new Course();
            c.setCCode(Integer.valueOf(courseId.getText()));
            mController = new ModelController(c);
            try {
                ResultSet rs = mController.get();
                if(rs.next()) {
                    // update message property
                    updateMessage(rs.getString(1));
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }
    }
    
    public void getCourseNameOnClick(){
        try {
            Thread t = new Thread(task);
            // To update the label
            courseCodeLbl.textProperty.bind(task.messageProperty());
            t.setDaemon(true); // Imp! missing in your code
            t.start();
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    

提交回复
热议问题