How to pack a Java program into an executable App in MacOS

要在MacOS內變成執行檔,首先要將Java files編譯成.class,再將所有class檔以command方式包裝成jar檔,再以某種固定的路徑包裝成.app的資料夾=> 就會自己變成app檔

1. 將java files編譯成class files
=> javac test.java

2. 把所有.class檔包進.jar檔
=> 1) 寫manifest.mf檔:內容

Main-Class: test

(需要後面空兩行)

=> 2) 以指令方式包成.jar檔
jar cvfm testApp.jar manifest.mf test.class

3. 測試jar可否執行
=> java -jar testApp.jar

(以上如果是有package的話,請參考http://it-easy.tw/java-jar/)

4. 開啟”Automator” => Choose “Application” => Search “AppleScript”
=> Drag “Run AppleScript” to right side

=>
on run {input, parameters}
set p to POSIX path of (path to me)
do shell script “java -jar ” & p & “/Contents/Java/TestApp.jar”
return input

end run

5. 將已做好的.icns檔替換到/Contents/Resources/AutomatorApplet.icns(檔名也要改)

完成圖:

6. AWTtest.java:
import java.awt.*;import java.awt.event.*;
class Attest{ 
public static void main(String[] args) {
        Frame frame = new Frame(“AWTDemo”);
        frame.addWindowListener(new AdapterDemo());
        frame.setLayout(new FlowLayout());
        Button button = new Button(“AWT1”);
        Checkbox checkbox = new Checkbox(“AWT2”);
        Choice choice = new Choice();
        choice.add(“AWT3”);
        Label label = new Label(“AWT4”);
        List list = new List();
        list.add(“AWT5”); 
        TextArea textarea = new TextArea(“AWT6”);
        TextField textfield = new TextField(“AWT7”);
        frame.add(button);
        frame.add(checkbox); 
        frame.add(choice);
        frame.add(label);
        frame.add(list);
        frame.add(textarea);
        frame.add(textfield);
                 frame.pack();
        frame.setVisible(true);
    }
}
class AdapterDemo extends WindowAdapter {
    public void windowClosing(WindowEvent e) {
        System.exit(0);
    }
}

參考:
1.
[Java]如何將編譯好的.class檔案打包成JAR?:http://it-easy.tw/java-jar/

2. 

Mac 下開發 Java 程式二三事:http://blog.ericsk.org/archives/317
3.

How to convert .jar to .app on Mac – a Java tutorial:https://www.youtube.com/watch?v=kwdK6Dg1a_Y

作者

RongSon

Graduate Student of CCU COMM Game Development, Network Communication, macOS/Ubuntu/Android, Arduino/Raspberry Pi/Intel Edison, Java/Python/C/C++

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *