簡體   English   中英

Java Swing - 如何在Mac上雙擊項目文件以打開我的應用程序並加載文件?

[英]Java Swing - How to double click a project file on Mac to open my application and load the file?

我創建了一個Mac Java Swing應用程序,並在“Info.plist”文件中為它設置了文件擴展名(* .pkkt),因此當雙擊該文件時,它會打開我的應用程序。

當我這樣做時,程序運行正常。 現在我需要在程序中加載(* .pkkt)項目,但文件路徑不作為參數傳遞給Mac中的main(...)方法,就像在Windows操作系統中一樣。

經過一番搜索,我找到了一個Apple處理jar“ MRJToolkitStubs ”,它有MRJOpenDocumentHandler接口來處理這些點擊的文件。 我已嘗試通過在主程序類中實現該接口來加載該文件,但它無法正常工作。 在程序啟動時永遠不會調用實現的方法。

這個界面如何運行?

-------------------------------------------------編輯:添加代碼示例

這是我正在使用的代碼:

 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;
    }
}

正如上面的評論中提到的“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
    }

}

在某個地方:

import com.apple.eawt.Application;

...

MacOpenHandeler myOpenHandeler = new MacOpenHandeler();
Application.getApplication().setOpenFileHandler(myOpenHandeler);

在Java 9上,使用Desktop.setOpenFileHandler()

專有的com.apple.eawt包已從最新版本的Java中刪除,並已合並到Desktop類的各種方法中。 對於您的具體示例:

import java.awt.desktop.OpenFilesHandler;
import java.awt.desktop.OpenFilesEvent;
import java.io.File;
import java.util.List;

public class MyOpenFileHandler implements OpenFilesHandler {

    @Override
    public void openFiles​(OpenFilesEvent e) {
        for (File file: e.getFiles​()) {
            // Do whatever
        }
    }
}

然后在其他地方添加:

Desktop.getDesktop().setOpenFileHandler(new MyOpenFileHandler());

OpenFilesEvent類還有一個getSearchTerm()方法。 假設一個人在macOS上使用Spotlight來搜索單詞“StackOverflow”,然后決定打開一個文檔。 使用此方法,您可以確定“StackOverflow”是他們搜索的單詞,並選擇對其執行某些操作(可能會突出顯示該單詞的第一個匹配項)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM