我创建了一个Mac Java Swing应用程序,并在"Info.plist"文件中为它设置了文件扩展名(*.pkkt),因此当双击该文件时,它会打开我的应用程序.
当我这样做时,程序运行正常.现在我需要在程序中加载(*.pkkt)项目,但文件路径不作为参数传递给Mac中的main(...)方法,就像在Windows操作系统中一样.
经过一番搜索,我找到了一个Apple处理jar" MRJToolkitStubs ",它有MRJOpenDocumentHandler接口来处理这些点击的文件.我已尝试通过在主程序类中实现该接口来加载该文件,但它无法正常工作.在程序启动时永远不会调用实现的方法.
这个界面如何运行?
-------------------------------------------------编辑:添加代码示例
这是我正在使用的代码:
Run Code Online (Sandbox Code Playgroud)public static void main( final String[] args ) { . . . MacOpenHandler macOpenHandler = new MacOpenHandler(); String projectFilePath = macOpenHandler.getProjectFilePath(); // Always Empty !! }
class MacOpenHandler implements MRJOpenDocumentHandler {
private String projectFilePath = "";
public MacOpenHandler () {
com.apple.mrj.MRJApplicationUtils.registerOpenDocumentHandler(this) ;
}
@Override
public void handleOpenFile( File projectFile ) {
try {
if( projectFile != null ) {
projectFilePath = projectFile.getCanonicalPath();
System.out.println( projectFilePath ); // Prints the path fine.
}
} catch (IOException e) {}
}
public String getProjectFilePath() {
return projectFilePath;
}
}
Run Code Online (Sandbox Code Playgroud)
正如上面的评论中提到的"getProjectFilePath()"总是空的!
您将需要使用Apple Java Extensions。
它们应该包含在 Mac OS X 上运行的任何 JDK 中,但文档有点难以获取。有关更多详细信息, 请参阅此答案。
具体来说,您需要制作一个OpenFilesHandeler.
此代码片段应该可以工作:
import com.apple.eawt.event.OpenFilesHandeler;
import com.apple.eawt.event.AppEvent;
import java.io.File;
import java.util.List;
class MacOpenHandler implements OpenFilesHandeler {
@Override
public void openFiles(AppEvent.OpenFilesEvent e) {
List<File> files = e.getFiles();
// do something
}
}
Run Code Online (Sandbox Code Playgroud)
还有某处:
import com.apple.eawt.Application;
...
MacOpenHandeler myOpenHandeler = new MacOpenHandeler();
Application.getApplication().setOpenFileHandler(myOpenHandeler);
Run Code Online (Sandbox Code Playgroud)