Search code examples
javalinuxswingintellij-ideagnome

How use system default icons pack in Java Swing?


I want use the default icons of my OS (kali linux gnome) in my Java application. I don't know if need to import the entire icons pack or if i just use some java swing method. Can you explain to me how to proceed?


Solution

  • The simplest approach is to just use an icon file directly:

    Icon icon = new ImageIcon("/usr/share/icons/Adwaita/32x32/actions/document-open.png");
    

    But really, icons are more complicated than that. There is a whole specification for how icon themes work. It includes a moderately complex algorithm for matching a desired icon by type and size.

    Java SE has no way to read SVG images that I know of, so either you would need to locate a robust, stable SVG library for Java, or you would need to ignore a theme’s scalable directories.

    The only way I know to obtain the end user’s current icon theme is with a command like:

    ProcessBuilder builder = new ProcessBuilder(
        "gsettings", "get", "org.gnome.desktop.interface", "icon-theme");
    builder.redirectError(ProcessBuilder.Redirect.INHERIT);
    
    String themeName;
    Process iconThemeCommand = builder.start();
    try (InputStream commandOutput = iconThemeCommand.getInputStream()) {
        themeName = new String(commandOutput.readAllBytes()).trim();
    }
    iconThemeCommand.waitFor();
    

    There is also the problem of being multi-platform. Obviously Windows and OSX won’t have a /usr/share/icons/Adwaita directory. You can bundle an icon theme tree with your application, but it’s probably under GPL or a similar license, so you would have to release your software under that license (or never release it at all) and include a copy of that license with your program, along with a notice to users where to obtain your program’s source.