我有一个问题。如何在JavaFX中执行异步数据库。我知道存在SwingWoker,但我读到我无法在JavaFX中使用它。我读到了关于Task但我可以将结果转换为ObservableList但我需要普通的LinkedList。 我正在尝试使用mysql数据库
我知道这个论坛在javafx中有很多关于数据库的回答,但所有结果都转换为ObservableList
感谢您的所有答案。
FlightControllerTask.java
public class FlightControllerTask extends Task<LinkedList<Flight>>{
private final static int MAX=10000;
ArrayList<Airport> airportList=new ArrayList<>()
@Override
protected LinkedList<Flight> call() throws Exception {
for (int i = 0; i < MAX; i++) {
updateProgress(i, MAX);
Thread.sleep(5);
}
LinkedList<Flight> flightList = new LinkedList<>();
Connection c ;
c = DBConnector.connect();
String SQL = "SELECT flight.idflight, airport.nameAirport, airport.nameAirport, flight.departureTime FROM flight INNER JOIN airport";
ResultSet rs = c.createStatement().executeQuery(SQL);
while(rs.next()){
flightList.add(new Flight(rs.getInt("idflight"), rs.getString("flightFrom"), rs.getString("flightTo"), rs.getTime("departureTime")));
}
return flightList;
}
FlightControllerService
public class FlightControllerService extends Service<LinkedList<Flight>>{
@Override
protected Task<LinkedList<Flight>> createTask() {
return new FlightControllerTask();
}
}
MainController.java
final FlightControllerService service= new FlightControllerService();
ReadOnlyObjectProperty<LinkedList<Flight>> flightList =service.valueProperty();
flightList.get();
答案 0 :(得分:0)
public class FlightControllerTask extends Task<LinkedList<Flight>>{
@Override
protected LinkedList<Flight> call() throws Exception {
// load data
return data;
}
}
// usage:
FlightControllerTask task = new FlightControllerTask();
task.setOnSucceeded(ev -> task.getValue());
new Thread(task).start();
现在task.getValue()
的部分是关键部分,使用此方法,您可以在准备好后立即检索使用任务计算的值(因此成功的挂钩)。