Search code examples
javaeclipseswingjlabel

Adding image to JLabel, and displaying Labels in a GridLayout


My current code, interestingly works with another IDE(JGrasp), although I am currently trying to create a game which uses networking. Eclipse allows networking on a single computer. For some reason, this method Im posted, which adds imagines to an array of JLabel, does not work with eclipse? I am new with eclipse and not sure why this is happening?

private JPanel createBoard()
{
    // Instantiate Panel with a GridLayout
    board = new JPanel();
    board.setLayout(new GridLayout(10,10));

    // Fill the Panel with an Array of Labels
    // Checks for exception
    boardSpotArray = new JLabel[100];
    try
    {
        for (int x = 0; x < boardSpotArray.length; x++)
        {
            boardSpotArray[x] = new JLabel();
            boardSpotArray[x].setIcon(new ImageIcon(x + ".jpg"));
            board.add(boardSpotArray[x]);

        }
    }
    catch (IndexOutOfBoundsException exception)
    {
        System.out.println("Array drawer not available, " + exception.getMessage());
    }

    // return panel
    return board;
}

Solution

  • If for example boardSpotArray[0] is "firstImage", then your relative file path will be "firstImage.jpg". In such a case with Eclipse, and without using any special loaders or resource getters, the IDE will first look for the image in the project root. So your file structure should look like this

    ProjectRoot
             firstImage.jpg    <-- image as direct child of project root
             src
             bin
    

    Edit:

    If your images are in the src folder

    ProjectRoot
            src
               0.jpg       <-- image in src
               1.jpg
               2.jpg
    

    Then your path should look like this

    new ImageIcon("src/" + x + ".jpg")