Java Swing Icon getIconFromExtension(String f, boolean folder)

Here you can find the source of getIconFromExtension(String f, boolean folder)

Description

get Icon From Extension

License

Open Source License

Declaration

public static Icon getIconFromExtension(String f, boolean folder) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import javax.swing.Icon;
import javax.swing.filechooser.FileSystemView;

public class Main {
    /**// w w  w . ja  v  a 2 s. co m
     * Cache of file icons
     */
    private static final Map<String, Icon> CACHE = new HashMap<String, Icon>();

    public static Icon getIconFromExtension(String f, boolean folder) {
        if (folder) {
            return getFolderIcon();
        } else {
            return getIconFromExtension(f);
        }
    }

    /**
     * Gets default icon from file extension
     * @param f String like test.png
     * @return
     */
    public static Icon getIconFromExtension(String f) {
        String extension;

        if (f.contains(".")) {
            extension = f.substring(f.lastIndexOf("."), f.length());
        } else {
            extension = "";
        }

        Icon icon = null;

        if (CACHE.containsKey(extension)) {
            icon = CACHE.get(extension);
        } else {
            try {
                File temp = File.createTempFile((new Random()).nextInt() + "", extension);
                icon = FileSystemView.getFileSystemView().getSystemIcon(temp);

                CACHE.put(extension, icon);

                temp.delete();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        return icon;
    }

    /**
     * Gets system default folder icon
     * @return
     */
    public static Icon getFolderIcon() {
        Icon icon;

        if (CACHE.containsKey("file-dir")) {
            icon = CACHE.get("file-dir");
        } else {
            File temp = new File(System.getProperty("java.io.tmpdir") + File.separator + "icon");
            temp.mkdirs();

            icon = FileSystemView.getFileSystemView().getSystemIcon(temp);

            CACHE.put("file-dir", icon);

            temp.delete();
        }

        return icon;
    }
}

Related

  1. getIcon(String name)
  2. getIcon(String name)
  3. getIcon(String name, boolean isGrayIcon)
  4. getIcon(String name, ClassLoader classLoader)
  5. getIconCheckBox(String iconPath, String pressIconPath, String rolloverIconPath, String selectedIconPath)
  6. getIconInterTrial()
  7. getIcono()
  8. getPressedExitIcon(int x, int y)
  9. getResourceIcon(Object target, String name)