get Icon - Java 2D Graphics

Java examples for 2D Graphics:Icon

Description

get Icon

Demo Code


import javax.swing.*;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

public class Main{
    /**//from   w w  w  .j  av  a2s .c  om
     * @return a named icon from file or resource bundle.
     */
    public static Icon getIcon(String name) {
        return getIcon(IconUtils.class, name);
    }
    /**
     * @return a named icon from file or resource bundle.
     */
    public static Icon getIcon(Class resourceClass, String name) {
        Image image = getImage(resourceClass, name);
        if (image != null) {
            return new ImageIcon(image);
        } else {
            return null;
        }
    }
    /**
     * @return a named image from file or resource bundle.
     */
    public static Image getImage(String name) {
        return getImage(IconUtils.class, name);
    }
    /**
     * @return a named image from file or resource bundle.
     */
    public static Image getImage(Class resourceClass, String name) {
        java.net.URL url = resourceClass.getResource(name);
        if (url != null) {
            return Toolkit.getDefaultToolkit().createImage(url);
        } else {
            showWarning("Image " + name + " could not be loaded.");
            return null;
        }
    }
    private static void showWarning(final String message) {

        if (EventQueue.isDispatchThread()) {
            JOptionPane.showMessageDialog(null, message, "Warning",
                    JOptionPane.WARNING_MESSAGE);
        } else {
            // must show message dialog in the event dispatch thread, otherwise can crash
            try {
                EventQueue.invokeAndWait(new Runnable() {
                    public void run() {
                        JOptionPane.showMessageDialog(null, message,
                                "Warning", JOptionPane.WARNING_MESSAGE);

                    }
                });
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }

    }
}

Related Tutorials