非常多,我試圖編寫一個簡單的程序,讓用戶選擇一個文件。不幸的是,通過Swing的JFileChooser有點過時了,所以我正在嘗試使用JavaFX FileChooser。目標是將FileGetter作爲線程運行,將文件數據傳輸到主類,然後從那裏繼續。布爾值不會從Object.getBoolean()更新;
主類:
package application;
import java.io.File;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
public class Main {
public static void main(String[] args) {
Thread t1 = new Thread(new FileGetter());
FileGetter fg = new FileGetter();
t1.start();
boolean isReady = false;
while(isReady == false){
isReady = FileGetter.getIsReady();
}
File file = FileGetter.getFile();
System.out.println(file.getAbsolutePath());
...
}
}
FileGetter類別:
package application;
import java.io.File;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
public class FileGetter extends Application implements Runnable {
static File file;
static boolean isReady = false;
@Override
public void start(Stage primaryStage) {
try {
FileChooser fc = new FileChooser();
while(file == null){
file = fc.showOpenDialog(primaryStage);
}
isReady = true;
Platform.exit();
} catch(Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
launch();
}
public static boolean getIsReady(){
return isReady;
}
public static File getFile(){
return file;
}
}
問題是,當用戶選擇了一個文件的isReady在while循環的值不更新爲true(原因我的目的是防止Main中的代碼繼續將文件設置爲空)。
任何幫助,替代建議或解釋爲什麼發生這種情況非常感謝!
在FileGetter volatile中創建'isReady'。 – Codebender
@Codebender工作!謝謝!只是好奇作爲一個方面的說明,出於某種原因,當我包括一個System.out.println(isReady)時它工作;在while循環中。任何人都知道這個的原因? –
FileGetter#start中的while循環是爲了確保用戶選擇文件,而Main Class中的while循環是爲了確保代碼在選擇文件之前不會繼續。但是,我可以在兩者中使用相同的條件語句,但我相信它是相同的概念。 –