Search code examples
javaarraysgraphics2d

Adding multiple images to GPanel with Java


Im building a blackjack game in java for school and I can't seem to figure out how to add the first four cards to the GPanel. The array of cards are shuffled and the strings in the array match the file name of the images. I can get the first card in the array to load but not the other three. Any help would be awesome.

public void paintComponent(Graphics g) {
        //System.out.println(gameInProgress);

        if(gameInProgress == true) {
            super.paintComponent(g);

            Graphics2D g2 = (Graphics2D) g;
            Image image = null;
            int i;
            currentPosition = 0;
            for (i = 0; i < 4; i++) {
                image = Toolkit.getDefaultToolkit().getImage("images/"+deck[currentPosition - i]+".png");
                currentPosition++;
            }
            g2.drawImage(image, 115, 5, 80, (int) 106.67, this);
            g2.finalize();
        }
    }

Solution

  • You have 3 main issues in your code.

    The first issue is caused by [currentPosition - i] because the result will always equal 0, so the image/card at array index 0 will be the only one that will ever be drawn.

    The second issue is that you only draw one image because g2.drawImage is only called after the for loop, instead it should be inside the for loop so that all 4 images/cards are drawn.

    The third issue is that you always draw your images in the same place, so even if you where drawing all 4 images you would only see the last one because it covers the previous ones.

    Try this, it should print all 4 images (Assuming you have a 435x112 panel):

    public void paintComponent(Graphics g) {
        //System.out.println(gameInProgress);
    
        if(gameInProgress == true) {
            super.paintComponent(g);
    
            //Add a couple new variables
            int x = 115;
    
            Graphics2D g2 = (Graphics2D) g;
            Image image = null;
            int i;
            for (i = 0; i < 4; i++) {
                image = Toolkit.getDefaultToolkit().getImage("images/"+deck[i]+".png");
                //New location of g2.drawImage
                //The X positions should change each time
                g2.drawImage(image, x, 5, 80, 107, this);
                //Change the X location of the next image
                x = x + 80;
            }
            //Moved g2.drawImage from here to above the bracket
            g2.finalize();
        }
    }