AWT (the Abstract Window Toolkit) is a Java GUI widget toolkit. Although Swing largely superseded AWT, the latter is still used alone or in combination with Swing components. This tutorial will demonstrate how to turn AWT programs into native executables using Liberica Native Image Kit (NIK).
Install Liberica NIK
Liberica NIK is a GraalVM-based native-image compiler supporting GraalVM versions 21 & 22 for Java 11 & 17. NIK Full version can be used to turn AWT/Swing applications into native images on Linux, Windows, and macOS.
For our demo, we will use Liberica NIK 22.3.1 for Java 17. Download the utility for your platform and follow the instructions to complete the installation. Set $PATH to Liberica NIK:
PATH=<path-to-nik>/bin:$PATH
Create an AWT app
Build a simple AWT application (the code was taken here):
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Sample extends Frame {
public Sample() {
Button btn = new Button("Button");
btn.setBounds(50, 50, 50, 50);
add(btn);
setSize(150, 150);
setTitle("Simple AWT window");
setLayout(new FlowLayout());
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
dispose();
}
});
}
public static void main(String args[]){
new Sample();
}
}
Add a maven plugin to build an executable jar:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<archive>
<manifest>
<mainClass>
Sample
</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
Go to the project directory and build a jar file with
mvn package
Build an AWT native image
You need to set java.awt.headless
property to false
Build a native image:
native-image -Djava.awt.headless=false -jar target/AwtDemo-1.0-SNAPSHOT-jar-with-dependencies.jar awtdemo
Run the image with
./awtdemo
AWT native image
If your app doesn’t use any resources, Reflection, JNI, or other features not supported by GraalVM, you don’t need to configure anything. Otherwise, explicitly provide resources or any classes used by reflection or serialization to the native-image
tool. For that purpose, run the application with Graal tracing agent to dump the resources and dynamic classes used by the application. After that, run the native-image
tool with configuration files that you generated.
More examples of turning desktop applications into native images can be found in our articles dedicated to Swing and JavaFX.
You can also use Liberica NIK with Spring Boot, Quarkus, and Micronaut.