Gabriel Logronio
Gabriel Logronio

Reputation: 23

Paint Image in JPanel using drawImage

may I ask your help? I'm having some trouble painting an image inside a JPanel. I used to create a class that extended JPanel and did this

public class Example extends JPanel {

    BufferedImage background;

    public Example () {

        background = loadImage();   
    }           

    private BufferedImage loadImage(){
        URL imagePath = getClass().getResource("Immagini/Board.png");
        BufferedImage result = null;
        try {
            result = ImageIO.read(imagePath);
        } catch (IOException e) {
            System.err.println("Errore, immagine non trovata");
        }

        return result;
    }

     @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Dimension size = getSize();
        g.drawImage(background, 0, 0,size.width, size.height,0, 0, background.getWidth(), background.getHeight(), null);

    }
}

And it was perfect, now i can't do that because my newExample class extends genericExample so can't extend JPanel too. I have JPanel panel = new JPanel() inside the newExample in which i'd like to paint like I did in the code above, how can I adapt it to use in this different situation?

Upvotes: 1

Views: 2035

Answers (1)

scsere
scsere

Reputation: 651

You can still reuse your Example class. Instead of JPanel panel = new JPanel(); you would use your overwritten panel class:

JPanel panel = new Example();

Another way would be to use an anonymous implementation of JPanel:

JPanel panel = new JPanel(){
    BufferedImage background = loadImage();

    private BufferedImage loadImage(){
        URL imagePath = getClass().getResource("Immagini/Board.png");
        BufferedImage result = null;
        try {
            result = ImageIO.read(imagePath);
        } catch (IOException e) {
            System.err.println("Errore, immagine non trovata");
        }
        return result;
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Dimension size = getSize();
        g.drawImage(background, 0, 0,size.width, size.height,0, 0, background.getWidth(), background.getHeight(), null);
    }
};

Note that you can't use a constructor in an anonymous class and it's bad for reusability.

Hope this helps a bit

Upvotes: 1

Related Questions