I am using Task class to run background task in javafx application to fetch the data from the database.
public class CustomTask extends Task<ObservableList<ObservableList>> {
TableView tableview;
ObservableList<ObservableList> data;
public CustomTask(TableView tableview) {
this.tableview = tableview;
}
@Override
protected ObservableList<ObservableList> call() throws Exception {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String SQL = "SELECT * from sell where Date='" + dateFormat.format(date) + "'";
ResultSet rs = DBConnect.getResultSet(SQL);
data = DBConnect.generateListDateFromTable(rs, true);
return data;
}
}
How to use the data object.
You declare a method's return type in its method declaration. Within the body of the method, you use the return statement to return the value. Any method declared void doesn't return a value and cannot contain a return statement. Any method that is not declared void must contain a return statement.
To use the return value when calling a method, it must be stored in a variable or used as part of an expression. The variable data type must match the return type of the method.
runLater. Run the specified Runnable on the JavaFX Application Thread at some unspecified time in the future. This method, which may be called from any thread, will post the Runnable to an event queue and then return immediately to the caller. The Runnables are executed in the order they are posted.
The javafx. concurrent package consists of the Worker interface and two basic classes, Task and Service , both of which implement the Worker interface. The Worker interface provides APIs that are useful for a background worker to communicate with the UI. The Task class is a fully observable implementation of the java.
Example 1 addEventHandler
MyResultObjectType result;
CustomTask task = new CustomTask();
task.addEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED,
new EventHandler<WorkerStateEvent>() {
@Override
public void handle(WorkerStateEvent t) {
result = task.getValue();
}
});
Example 2 setOnSucceeded
MyResultObjectType result;
CustomTask task = new CustomTask();
task.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
@Override
public void handle(WorkerStateEvent t) {
result = task.getValue();
}
});
Example 3 addListener
task.valueProperty().addListener(new ChangeListener<Task>() {
@Override
public void changed(ObservableValue<? extends mytype> obs,
mytype oldValue, mytype newValue) {
if (newValue != null) {
System.out.println("Result = " + newValue);
}
}
});
Bind to the Task's value property OR provide a task.setOnSucceeded() event handler and call task.getValue() in the provided event handler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With