How to use the return value of a method to call the Task class in Javafx

I am using the Task class to run a background task in a javafx application to retrieve data from a 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 a data object.

+7
source share
2 answers

Bind the property value to the task OR provide task.setOnSucceeded () and a call to task.getValue () in the provided event handler.

+12
source

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); } } }); 
+20
source

All Articles