呃......在Uluk Biy的提示之後,我開始嘗試。 6個小時後,我做了這樣的技巧:
這是我的方法,它返回所需的任務。
public static Task saveNewAccoounting(final Accounting a){
Task<Integer> saveNewAccountingTask = new Task<Integer>() {
@Override protected Integer call() throws Exception {
try {
run.logger.log(Level.FINE, "Started saveNewAccounting Task!");
PreparedStatement newAcc;
newAcc = Connect.con.prepareStatement("INSERT INTO `ACCOUNTING`(`ACCNUMBER`, `ACCDATE`, `SHOP`, `CUSTOMER`, `CATEGORIES`, `WRITTENBY`, `DATE`, `DESCRIPTION`, `NOTE`, `PRICE`, `FILEORIGINAL`, `FILEBYTE`) VALUES (null,null,?,?,?,?,?,?,?,?,?,?)");
newAcc.setInt(1, a.getShop());
newAcc.setInt(2, a.getCustomer());
newAcc.setInt(3, a.getCategories());
newAcc.setInt(4, Credentials.getUserid());
newAcc.setDate(5, a.getDate());
newAcc.setString(6, a.getDescription());
if (a.getNote().equals("")){
newAcc.setNull(7, java.sql.Types.VARCHAR);
} else {
newAcc.setString(7, a.getNote());
}
newAcc.setDouble(8, a.getPrice());
if(a.getAttachment() != null){
newAcc.setString(9, a.getAttachment().getName());
newAcc.setBlob(10, new FileInputStream(a.getAttachment()));
} else {
newAcc.setNull(9, java.sql.Types.VARCHAR);
newAcc.setNull(10, java.sql.Types.BLOB);
}
if(!newAcc.execute()){
newAcc.close();
run.logger.log(Level.FINE, "Successfully completed saveNewAccounting Task!");
return 1;
} else {
newAcc.close();
run.logger.log(Level.FINE, "Completed saveNewAccounting Task with Failures!");
return 0;
}
} catch (SQLException ex) {
run.dblogger.log(Level.SEVERE, ex.getMessage());
run.logger.log(Level.FINE, "Completed saveNewAccounting Task with Failures!");
return 0;
} catch (FileNotFoundException f){
run.iologger.log(Level.SEVERE, f.getMessage());
run.logger.log(Level.FINE, "Completed saveNewAccounting Task with Failures!");
return 0;
}
}
};
return saveNewAccountingTask;
}
你所要做的就是使用返回的任務實例化一個線程並執行它。
//Make your Progress visible here
final Task saveTask = SaveTasks.saveNewAccoounting(acc);
Thread saveThread = new Thread(saveTask);
saveThread.setDaemon(true);
saveThread.start();
現在添加一個監聽器到任務和東西完成。
saveTask.setOnSucceeded(new EventHandler() {
@Override
public void handle(Event t) {
Progress.close();
if (saveTask.getValue() == 1){
//SUCCESS
} else {
//FAIL
}
}
});
希望這對未來有幫助。
數據庫操作應該在除JavaFX UI Thread之外的另一個線程中完成。否則,UI將暫時等待/凍結,直到數據庫任務完成。調查此[搜索結果](http://stackoverflow.com/search?q=%5Bjavafx%5D+or+%5Bjavafx-2%5D+progress+bar+task+is%3Aquestion)。 –
好吧......現在它開始變得複雜了,我想......但是謝謝你的提示! – downdrown