[英]OS X El Capitan 10.11.3 Java 8 FileDialog doesn't open
在用下一個代碼片段調用java.awt.FileDialog時遇到問題。 OS X微調器不斷旋轉,並且沒有任何變化(Finder無法打開)
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
primaryStage.setTitle("CSV Parser");
Button button = new Button();
button.setText("Import Translations");
button.setOnAction(event -> {
String openFile = openFile();
System.out.println("Open file " + openFile);
});
VBox vbox = new VBox();
vbox.setPadding(new Insets(10));
vbox.setSpacing(8);
vbox.getChildren().add(button);
primaryStage.setScene(new Scene(vbox));
primaryStage.show();
}
public static String openFile() {
JFrame parentFrame = getJFrame("JFrame");
String osName = System.getProperty("os.name");
if (osName.toLowerCase().contains("mac")) {
FileDialog fileDialog = new FileDialog(parentFrame);
FilenameFilter csvFilter = (dir, name) -> name.endsWith(".csv");
fileDialog.setFilenameFilter(csvFilter);
fileDialog.setFile("*.csv");
fileDialog.setMode(FileDialog.LOAD);
String dirHome = System.getProperty("user.home");
fileDialog.setDirectory(dirHome);
fileDialog.setVisible(true);
boolean isShowing = fileDialog.isShowing();
if (isShowing) {
File fileToOpen = new File(fileDialog.getFile());
String path = fileToOpen.getAbsolutePath();
parentFrame.dispatchEvent(new WindowEvent(parentFrame, WindowEvent.WINDOW_CLOSING));
return path;
} else {
parentFrame.dispatchEvent(new WindowEvent(parentFrame, WindowEvent.WINDOW_CLOSING));
return null;
}
}
return null;
}
private static JFrame getJFrame(String name) {
JFrame parentFrame = new JFrame(name);
parentFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
ex.printStackTrace();
}
return parentFrame;
}
public static void main(String[] args) {
launch(args);
}
}
我只需要具有選擇具有適當擴展名的文件(而不是文件夾)的能力,對話框的外觀就沒有任何意義,但是我想在沒有任何外部庫的情況下實現它。 我將不勝感激。
您的對話框已鏈接到新框架(不可見)...您應使用null
參數設置對話框的構造函數,或使用邏輯上應將對話框鏈接到當前框架的引用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.