我正在使用Task类在javafx应用程序中运行后台任务来从数据库中获取数据。
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;
}
}
如何使用数据对象。
答案 0 :(得分:25)
示例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();
}
});
示例2 setOnSucceeded
MyResultObjectType result;
CustomTask task = new CustomTask();
task.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
@Override
public void handle(WorkerStateEvent t) {
result = task.getValue();
}
});
示例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);
}
}
});
答案 1 :(得分:16)
绑定到任务的value property或提供task.setOnSucceeded()事件处理程序并在提供的事件处理程序中调用task.getValue()。