javaswingunsatisfiedlinkerror

Simple java swing program not running and showing exception


I tried to run this program:

 import javax.swing.*;
    public class HelloSwing {
    public static void main(String[] args) {
    JFrame frame = new JFrame("Hello Swing");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300, 100);
    frame.setVisible(true);
    }

}

and got this stacktrace:

Exception in thread "main" java.lang.UnsatisfiedLinkError: Can't load library: /usr/lib/jvm/java-16-openjdk-amd64/lib/libawt_xawt.so
    at java.base/java.lang.ClassLoader.loadLibrary(ClassLoader.java:2387)
    at java.base/java.lang.Runtime.load0(Runtime.java:746)
    at java.base/java.lang.System.load(System.java:1857)
    at java.base/jdk.internal.loader.NativeLibraries.load(Native Method)
    at java.base/jdk.internal.loader.NativeLibraries$NativeLibraryImpl.open(NativeLibraries.java:383)
    at java.base/jdk.internal.loader.NativeLibraries.loadLibrary(NativeLibraries.java:227)
    at java.base/jdk.internal.loader.NativeLibraries.loadLibrary(NativeLibraries.java:169)
    at java.base/jdk.internal.loader.NativeLibraries.findFromPaths(NativeLibraries.java:310)
    at java.base/jdk.internal.loader.NativeLibraries.loadLibrary(NativeLibraries.java:280)
    at java.base/java.lang.ClassLoader.loadLibrary(ClassLoader.java:2392)
    at java.base/java.lang.Runtime.loadLibrary0(Runtime.java:808)
    at java.base/java.lang.System.loadLibrary(System.java:1893)
    at java.desktop/java.awt.Toolkit$2.run(Toolkit.java:1389)
    at java.desktop/java.awt.Toolkit$2.run(Toolkit.java:1387)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:312)
    at java.desktop/java.awt.Toolkit.loadLibraries(Toolkit.java:1386)
    at java.desktop/java.awt.Toolkit.<clinit>(Toolkit.java:1419)
    at java.desktop/java.awt.Component.<clinit>(Component.java:622)
    at com.masud.HelloSwing.main(HelloSwing.java:6)

I am using ubuntu 20.04 and openjdk16. It looks like a library file is missing.what will be my best course of action?


Solution

  • Make sure you don't rely on openjdk-16-headless. If you are running on headless, the issue may be caused by missing libraries.

    Headless excludes the window libraries to A, save resources and B because it runs in cli and probably without a monitor.

    So why would headless have window libraries if there is cli only anyways.

    To fix this issue, just open a terminal and enter

    apt remove openjdk-16-headless -y
    
    apt install openjdk-16 -y
    
    OR
    
    apt install default-jdk default-jre -y