Search code examples
javaimagejbutton

Need help batch adding images with 00 in name of filepath (Java)


I'm having trouble batch adding images to a JButton grid. I'm trying to use a for loop who's variable is used in the string name.

The names of the images are like:

32px-Shuffle001.png

32px-Shuffle821.png

etc.

Here's the part of the code that I'm trying to add in images with. The third setIcon works, but the first two don't. I'm confused on why this is.

Additionally, the image files are not consecutive numbers. For example, I have 001,002,003,004,005, but not 007,008, then continuing at 009,010. I'm trying to figure out a good way to make it skip to the next available image.

Overall, this code is for a match 3 puzzle solver, and this is a selection grid for icons to put on the puzzle grid, so I need to be able to call the correct image associated to a button ID.

            for (int i = 0; i < 1000; i++) {
            JButton selectionClicky = new JButton();
            if (i < 10) {
                selectionClicky.setIcon(new ImageIcon("src/img/32px-Shuffle" + "00"
                        + i + ".png"));
            }
            if (i < 100){
                selectionClicky.setIcon(new ImageIcon("src/img/32px-Shuffle"+ "0"
                        + i + ".png"));
            }
            if (i < 1000){
                selectionClicky.setIcon(new ImageIcon("src/img/32px-Shuffle"
                        + i + ".png"));
            }
            selectionClicky.setFocusable(false);
            selectionMainPanel.add(selectionClicky);
            selectionButtonList.add(selectionClicky);
        }

Solution

  • Don't ever use src in any path reference, this is a good indication that things will go wrong, instead use Class#getResource or Class#getResourceAsStream depending on your requirements.

    Basically, the general idea would be to test if the resource actually existed before trying to load it, for example...

    String path = String.format("/img/32px-Shuffle%03d", i);
    URL resource = getClass().getResource(path);
    if (resource != null) {
        BufferedImage img = ImageIO.read(resource);
        selectionClicky.setIcon(new ImageIcon(img));
    }
    

    Generally, ImageIO is preferred over using ImageIcon, mostly because ImageIO throws an IOException when the image can't be loaded for some reason (instead of failing silently) and won't return until the image is fully loaded

    See Reading/Loading an Image for more details about ImageIO