Como adicionar imagem em um JPanel

4 respostas
J

Olá pessoal, estou querendo adicionar imagens em JPanel
Eis que encontro um tópico aki do GUJ com o seguinte código (do ViniGodoy eu acho)

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

/**
 * A panel that contains a background image. 
 * The background image is automatically sized to fit in the panel.
 */
public class JImagePanel extends JPanel
{
    BufferedImage background = null;
    
    /** Creates a new panel with the given background image.
      * @param img The background image. */
    public JImagePanel(BufferedImage img)
    {
        if (img == null)
            throw new NullPointerException("Buffered image cannot be null!");
        this.background = img;
    }

    /** Creates a new panel with the given background image.
      * @param img The background image. 
      * @throws IOException, if the image file is not found.
      */
    public JImagePanel(File imgSrc) throws IOException
    {
        this(ImageIO.read(imgSrc));
    }

    /** Creates a new panel with the given background image.
      * @param img The background image. 
      * @throws IOException, if the image file is not found.
      */
    public JImagePanel(String fileName) throws IOException
    {
        this(new File(fileName));
    }
    
    @Override
    protected void paintComponent(Graphics g)
    {        
	super.paintComponent(g);
        Graphics2D g2d = (Graphics2D)g.create();
        g2d.drawImage(background, 0, 0, this.getWidth(), this.getHeight(), null);
        g2d.dispose();        
    }    
}

Eu não consegui entender algumas coisas, fui lendo os comentários do pessoal lá mas nao entendi como e onde usar o método para adicionar uma imagem no JPanel
Se alguem pudesse me explicar pra entender legal mesmo, eu agradeço

4 Respostas

Marky.Vasconcelos

O JImagePanel faz parte do Towel agora, eu fiz um post ensinando como usar.

J

eu entendi aquele código que vc apresentou lá

mas eu fui fazer um teste aki, e me gerou o seguinte erro

Exception in thread "main" javax.imageio.IIOException: Can't read input file! at javax.imageio.ImageIO.read(Unknown Source) at TesteImagem.loadImage(TesteImagem.java:26) at TesteImagem.main(TesteImagem.java:14)

Aquele jar era pra adicionar na biblioteca?

acho q não coloquei o jar no lugar certo XD

Marky.Vasconcelos

Posta o codigo de TesteImagem.

J

Consegui aki mano
brigadão pela ajuda aí

Criado 5 de dezembro de 2011
Ultima resposta 6 de dez. de 2011
Respostas 4
Participantes 2