gpt4 book ai didi

macos - 通过双击文件将参数传递给JavaFx应用程序

转载 作者:行者123 更新时间:2023-12-04 04:04:56 25 4
gpt4 key购买 nike

我创建了一个JavaFX应用程序,部署了.app文件,它运行良好。然后,我将操作系统设置为使用我的应用程序打开具有特定扩展名的所有文件。我的问题是,当我双击文件时,可以打开我的应用程序,但是我不知道哪个文件打开了该文件。

我尝试使用getParameters().getRaw()函数检查应用程序参数,但它始终返回空列表。

有人知道如何检索打开应用程序的文件的路径吗?

最佳答案

我终于找到了解决此问题的方法。

为了回答这个问题,我创建了一个示例应用程序,该应用程序由三个类组成:

Launcher
MyApp
Handler_OpenFile

MyApp是扩展javafx.application.Application类的类,Handler_OpenFile用于处理双击事件,最后Launcher是包含主事件的类。

Launcher.java:此类必须存在,因为如果在扩展javafx.application.Application的类中定义了main,则OpenFilesEvent将无法正常工作(更确切地说,只有在已经打开应用程序的情况下,OpenFilesEvent才会被触发)。
public class Launcher {
public static void main(String[] args) {
if (System.getProperty("os.name").contains("OS X")){
com.apple.eawt.Application a = com.apple.eawt.Application.getApplication();
Handler_OpenFile h_open = new Handler_OpenFile();
a.setOpenFileHandler(h_open);
Application.launch(Main.class, args);
}
}
}

Handler_OpenFile.java:此类定义一个静态变量,该变量存储打开应用程序的File的值。这可能不是最好的解决方案,但这是我现在可以使它工作的唯一方法。
public class Handler_OpenFile implements OpenFilesHandler {
public static File file = null;

@Override
public void openFiles(OpenFilesEvent e) {
for (File file : e.getFiles()){
this.file = file;
}
}
}

MyApp.java:此类将能够访问在Handler_OpenFile类中分配的静态值并检索打开文件的绝对路径。
public class MyApp extends Application {
@Override
public void start(Stage primaryStage) {

Logger logger = Logger.getLogger("log");
FileHandler fh;

try {
// This block configure the logger with handler and formatter
fh = new FileHandler("../Logfile.log");
logger.addHandler(fh);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);

// the following statement is used to log any messages
logger.info("Application launched from: " + Handler_OpenFile.file.getAbsolutePath());

} catch (SecurityException | IOException exception) {
exception.printStackTrace();
}


try {
BorderPane root = new BorderPane();
Scene scene = new Scene(root,400,400);
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
}

最后,在创建捆绑包的build.xml文件中,您将必须添加文件关联(在本示例中,扩展名为.zzz的文件):
<fx:info title="Sample" vendor="me">
<fx:association extension="zzz" description="Sample Source"/>
</fx:info>

这仅适用于Java(8u40)的最新更新: documentation at this link。对于以前的版本,您必须像在 Apple Java Extensions documentation中所说的那样在包中手动更改info.plist。

关于macos - 通过双击文件将参数传递给JavaFx应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29101472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com