2

I've got a simple swing application with a JFrame that holds various components. On the JFrame I have a custom toolbar class that extends JPanel. On the JPanel I plan on adding buttons with image icons. My directory structure is as follows:

  • Project/src/gui (Package holds source files for application)
  • Project/src/images (Package holds a jar file jlfgr-1_0.jar with button icons and /or individual images files)

The issue is that I want to avoid copying the individual image files to the images package. I'd rather somewhow just load the images directly from the jar file. I've got private method that returns the appropriate icon. This method works, for example if I drag an image file to the images package and call:

    button.setIcon(createIcon("/images/Save16.gif"));

private ImageIcon createIcon(String path) {
    URL url = getClass().getResource(path);
    ImageIcon icon = new ImageIcon(url);

    if(url == null) {
        System.err.println("Unable to load image: " + path);
    }
    return icon;

I know this is basic, but how can I get my images directly from the jar file in my current setup? Thanks.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
jrreid
  • 81
  • 1
  • 3
  • possible duplicate of [Loading images from jars for Swing HTML](http://stackoverflow.com/questions/6373621/loading-images-from-jars-for-swing-html) – Smutje Sep 21 '14 at 17:25
  • That code is *already* loading the images from the application class-path in the way we would load resources from a Jar! – Andrew Thompson Sep 21 '14 at 23:34

2 Answers2

1

You can read the image from the stream, thanks to javax.imageio.ImageIO:

private ImageIcon createIcon(String path) {
    BufferedImage image = ImageIO.read(getClass().getResourceAsStream(path));
    ImageIcon icon = new ImageIcon(image);
    return icon;
}
Nicolas Albert
  • 2,586
  • 1
  • 16
  • 16
0

This is another way. The images are at location src/images

BufferedImage myPicture = null;
try {
    myPicture = ImageIO.read(this.getClass().getResource("images/Picture2.png"));
} catch (IOException e) {
    // TODO Auto-generated catch block
    try {
        myPicture = ImageIO.read(this.getClass().getResource("images/broken_image.jpg"));
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
panel.add(picLabel);
Tunaki
  • 132,869
  • 46
  • 340
  • 423
mattyman
  • 351
  • 2
  • 16