Java 如何在所有窗口上打开文件对话框
我有一个Java Swings应用程序,可以在其中打开文件浏览器对话框 对于Windows,我使用JFileChooser和JDialog,但在MAC中使用它们会挂起应用程序,因此我在MAC中使用FileDialog 这是我正在使用的代码:Java 如何在所有窗口上打开文件对话框,java,macos,filedialog,Java,Macos,Filedialog,我有一个Java Swings应用程序,可以在其中打开文件浏览器对话框 对于Windows,我使用JFileChooser和JDialog,但在MAC中使用它们会挂起应用程序,因此我在MAC中使用FileDialog 这是我正在使用的代码: Frame frame = null; FileDialog fd = new FileDialog(frame, "Select Cover Photo", FileDialog.LOAD); fd.setF
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也没有帮助
那么,我怎样才能在所有打开的应用程序之上打开它呢?我不明白为什么在MAC上使用JFileChooser会挂起你的应用程序……它不应该挂起,但我再次读到,由于EDT,Swing会在MAC上做奇怪的事情。但我个人无法证实这一点,因为我从未在MAC电脑上工作过 一种解决方案可能是在单独的线程中运行该对话框,从而允许JFileChooser独立于EDT运行,因此不会对其造成任何威胁 至于隐藏在Swing应用程序后面的文件选择器对话框,我认为这可能是因为应用程序的JFrame设置为始终在顶部,即使文件选择器对话框被认为是模态的(实际上是)但这并不意味着如果将null用作其父组件,它将显示在所有内容之上。对话框的父对象本身也应设置为始终位于顶部。无论对话框显示在什么操作系统中,通常都会出现这种情况。无论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!");
}
}
});