ResTest.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.URL;

/**
Demonstrate loading resources from JAR file.
*/
public class ResTest extends JFrame
{
    public static void main(String[] argv)
    {
        ResTest t = new ResTest();
        t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        t.show();
    }

    public ResTest()
    {
        Toolkit kit = Toolkit.getDefaultToolkit();
        Dimension ss = kit.getScreenSize();
        setSize(ss.width/2,ss.height/2);
        setLocation(ss.width/4,ss.height/4);
        setTitle("CISC370-011 -- Resource loading demo");

        Container cp = getContentPane();

        JMenuBar mbar = new JMenuBar();
        setJMenuBar(mbar);
        JMenu filemenu = new JMenu("File");
        mbar.add(filemenu);
        JMenuItem exitItem = new JMenuItem("Exit");
        filemenu.add(exitItem);
        exitItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
                { System.exit(0); }
            });
        JMenu imageMenu = new JMenu("Images");
        mbar.add(imageMenu);

        String pics[] = {
            "marvel.gif",
            "images/barnie_3.jpg",
            "images/inkie_3.jpg",
            "images/inkie_6.jpg",
            "images/p0207210741b.jpg",
            "images/P6150036.JPG",
            };

        // Create a label to show the resource name.
        JLabel textlabel =
            new JLabel(pics[0],JLabel.CENTER);
        cp.add(textlabel,BorderLayout.SOUTH);

        // Create a static image label.
        ImageIcon icon =
            new ImageIcon(getClass().getResource(pics[0]));
        JLabel iconlabel = new JLabel(icon);
        cp.add(iconlabel,BorderLayout.CENTER);

        JPanel jp = new JPanel();
        for (int i=0; i<pics.length; i++) {
            ResAction action = 
                new ResAction(pics[i],getClass(),textlabel,iconlabel);
            imageMenu.add(action);
            }
        cp.add(jp,BorderLayout.NORTH);
    }
}


class ResAction extends AbstractAction
{
    public ResAction(
        String resname,
        Class baseclass,
        JLabel textlabel,
        JLabel iconlabel)
    {
        putValue(Action.NAME,resname);
        this.resname = resname;
        this.baseclass = baseclass;
        this.textlabel = textlabel;
        this.iconlabel = iconlabel;
    }

    public void actionPerformed(ActionEvent e)
    {
        URL url = baseclass.getResource(resname);
        if (url != null) {
            ImageIcon pict = new ImageIcon(url);
            iconlabel.setIcon(pict);
            textlabel.setText(resname);
            }
    }

    private String resname = null;
    private Class baseclass = null;
    private JLabel textlabel = null;
    private JLabel iconlabel = null;
}