如何在所有 windows 之上打开 FileDialog

How to open FileDialog on top of all windows

我有一个 Java Swings 应用程序,我在其中打开文件浏览器对话框。

对于 Windows,我正在使用 JFileChooser 和 JDialog,但是在 MAC 中使用它们会挂起应用程序,因此我将 FileDialog 用于 MAC。

这是我使用的代码:

        Frame frame = null;
        FileDialog fd = new FileDialog(frame, "Select Cover Photo", FileDialog.LOAD);
        fd.setFilenameFilter((File dir, String name) -> name.endsWith(".jpg"));
        fd.setAlwaysOnTop(true);
        fd.setVisible(true);
        String filename = new File(fd.getDirectory(), fd.getFile()).getAbsolutePath();

这在 MAC 中也能正常工作,但只有当我打开任何浏览器时,它才会在它后面打开,而不是在它上面打开。

使用 Frame not as null 也没有帮助。

那么如何在所有打开的应用程序之上打开它?

我不明白为什么使用 JFileChooser 在 MAC...它不应该但是我又读到 Swing can 由于 EDT 在 MACs 上做奇怪的事情。但是,我无法亲自确认这一点,因为我从未在 MAC.

上工作过

一个解决方案可能是 运行 单独线程中的对话框,从而允许 JFileChooser 独立于 EDT 运行,因此不会对其构成任何威胁。

至于您的文件选择器对话框隐藏在您的 Swing 应用程序后面,我认为这可能是因为您的应用程序的 JFrame 设置为 Always-On-Top 并且即使 FileChooser 对话框被认为是模态的(它确实如此)并不意味着如果 null 用作其父组件,它将显示在所有内容之上。对话框的父级本身也应设置为 Always-On-Top。无论对话框显示在什么操作系统中,通常都是这种情况。无论 JFileChooser 或 JOptionPane(等)对话框可能用于父级,或者实际上根本没有父级,以下代码都应该有效:

final JFrame iFRAME = new JFrame();
iFRAME.setAlwaysOnTop(true);    // ****
iFRAME.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
iFRAME.setLocationRelativeTo(null);
iFRAME.requestFocus();

JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
int returnValue = jfc.showOpenDialog(iFRAME);
iFRAME.dispose();
if (returnValue == JFileChooser.APPROVE_OPTION) {
    File selectedFile = jfc.getSelectedFile();
    // Display selected file in console
    System.out.println(selectedFile.getAbsolutePath());
}
else {
    System.out.println("No File Selected!");
}

事实上,当 运行 在 MAC 时您的应用程序崩溃,您可能想试试这个:

final JFrame iFRAME = new JFrame();
iFRAME.setAlwaysOnTop(true);    // ****
iFRAME.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
iFRAME.setLocationRelativeTo(null);
iFRAME.requestFocus();

EventQueue.invokeLater(new Runnable() {
    @Override
    public void run() {
        JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
        int returnValue = jfc.showOpenDialog(iFRAME);   // ****
        iFRAME.dispose();
        if (returnValue == JFileChooser.APPROVE_OPTION) {
            File selectedFile = jfc.getSelectedFile();
            // Display selected file in console
            System.out.println(selectedFile.getAbsolutePath());
        }
        else {
            System.out.println("No File Selected!");
        }
    }
});