简体   繁体   English

OS X El Capitan 10.11.3 Java 8 FileDialog无法打开

[英]OS X El Capitan 10.11.3 Java 8 FileDialog doesn't open

I faced with issue during invoking java.awt.FileDialog with next snippet of code. 在用下一个代码片段调用java.awt.FileDialog时遇到问题。 OS X spinner is constantly spinning and nothing change (Finder doesn't open) 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);
}
}

I need just to have ability to select a file with appropriate extension (not a folder), the appearance of dialog doesn't have a bi sense, but I want to implement it without any external libs . 我只需要具有选择具有适当扩展名的文件(而不是文件夹)的能力,对话框的外观就没有任何意义,但是我想在没有任何外部库的情况下实现它。 I would be appreciate for any help. 我将不胜感激。

您的对话框已链接到新框架(不可见)...您应使用null参数设置对话框的构造函数,或使用逻辑上应将对话框链接到当前框架的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM