Onde está o erro?

Quando tento colocar uma imagem no plano de fundo da minha a aplicação, a imagem simplesmente não aparece!

Codigo das classes:

Classe que inicializa a imagem:

package Classes;

import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.TexturePaint;
import java.awt.geom.Rectangle2D;
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
{
    private BufferedImage image = null;
    private FillType fillType = FillType.RESIZE;

    /**
     * Creates a new panel with the given background image.
     * 
     * @param img The background image.
     */
    public JImagePanel(BufferedImage img)
    {
        setImage(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));
    }

    /**
     * Changes the image panel image.
     * 
     * @param img The new image to set.
     */
    public final void setImage(BufferedImage img)
    {
        if (img == null)
            throw new NullPointerException("Buffered image cannot be null!");

        this.image = img;
        invalidate();
    }

    /**
     * Changes the image panel image.
     * 
     * @param img The new image to set.
     * @throws IOException If the file does not exist or is invalid.
     */
    public void setImage(File img) throws IOException
    {
        setImage(ImageIO.read(img));
    }

    /**
     * Changes the image panel image.
     * 
     * @param img The new image to set.
     * @throws IOException If the file does not exist or is invalid.
     */
    public void setImage(String fileName) throws IOException
    {
        setImage(new File(fileName));
    }

    /**
     * Returns the image associated with this image panel.
     * 
     * @return The associated image.
     */
    public BufferedImage getImage()
    {
        return image;
    }

    /**
     * Changes the fill type.
     * 
     * @param fillType The new fill type
     * @throws IllegalArgumentException If the fill type is null.
     */
    public void setFillType(FillType fillType)
    {
        if (fillType == null)
            throw new IllegalArgumentException("Invalid fill type!");

        this.fillType = fillType;
        invalidate();
    }

    public static enum FillType
    {
        /**
         * Make the image size equal to the panel size, by resizing it.
         */
        RESIZE
        {
            @Override
            public void drawImage(JPanel panel, Graphics2D g2d,
                    BufferedImage image)
            {
                g2d.drawImage(image, 0, 0, panel.getWidth(), panel.getHeight(),
                        null);
            }
        },

        /**
         * Centers the image on the panel.
         */
        CENTER
        {
            @Override
            public void drawImage(JPanel panel, Graphics2D g2d,
                    BufferedImage image)
            {
                int left = (panel.getHeight() - image.getHeight()) / 2;
                int top = (panel.getWidth() - image.getWidth()) / 2;
                g2d.drawImage(image, top, left, null);
            }

        },
        /**
         * Makes several copies of the image in the panel, putting them side by
         * side.
         */
        SIDE_BY_SIDE
        {
            @Override
            public void drawImage(JPanel panel, Graphics2D g2d,
                    BufferedImage image)
            {
                Paint p = new TexturePaint(image, new Rectangle2D.Float(0, 0,
                        image.getWidth(), image.getHeight()));
                g2d.setPaint(p);
                g2d.fillRect(0, 0, panel.getWidth(), panel.getHeight());
            }
        };

        public abstract void drawImage(JPanel panel, Graphics2D g2d,
                BufferedImage image);
    }
}

trecho do codigo da interface!

try{
            jPanel1 = new JImagePanel("D:\Pisom\JAVA - projetos\GRÁFICA\Projeto\Grafica\TelaFundo.jpg");  // <-- AKI
            jLabel1 = new javax.swing.JLabel();
            btnEstoque = new javax.swing.JButton();
            lblEstoque = new javax.swing.JLabel();
            
            // Iniciação dos outros componetes da frame!

        }
        catch(IOException e){
        }

Se você ignorar os erros, vai ficar difícil saber o que aconteceu.

Esse código aqui, ignora completamente o erro que explica o problema:

catch(IOException e){ }

No mínimo, troque-o para:

catch(IOException e){ e.printStackTrace(); }

Ou troque-o para:

catch(IOException e){ throw new RuntimeException(e); //Não deve ocorrer }

E depois poste que erro dá para a gente.

Aliás, nunca, jamais, never, ignore exceptions dessa forma. Dê uma lida nesses artigos, vão te ajudar:
http://blog.caelum.com.br/2006/10/07/lidando-com-exceptions/



Realmente sem o Stack Trace fica difícil rsrs.

Coloquei o e.printStackTrace, mas naum apareceu nada :confused:

Ok, e onde está o código onde vc inclui o JPanel1 no seu JFrame? Tem certeza que ele está visível?

Naum naum, eh uma outra classe!

Eu instanciei outro construtor!

ola amigos.
estou acompanhando a discussao. E em relação ao “catch”. já vi bastante catch, sem nada também e funciona direitinho.
Até no livro que eu tenho de Java6 (pedir mais detalhes, se de interesse). Os exemplo, estão com catchs, vazios e funcionam.
Quanto ao erro também não sei qual é, já descobriram?

Mas gostaria de dizer qu e eu adiciono imagens a painéis, facilmente, com o
[color=red]ImageIcon [/color]para iniciar… a imagem (solicitar informação se necessário)
e em um botao, ou em uma label, uso o [color=darkred]label.setIcon(imagem)[/color]alternativa?
coments…

Já ouvi falar desta label com o icone, mas naum ia ficar meio gambiarrado!

Tem algum exemplo que eu possa dar uma olhada?
vlw!

[quote=raghy]ola amigos.
estou acompanhando a discussao. E em relação ao “catch”. já vi bastante catch, sem nada também e funciona direitinho.
Até no livro que eu tenho de Java6 (pedir mais detalhes, se de interesse). Os exemplo, estão com catchs, vazios e funcionam.
[/quote]

Funcionar funciona. Mas não é porque funciona que é certo. Nos exemplos, eles omitem o tratamento simplesmente pra simplificar, já que tratar exceptions não deve ser o foco do exemplo.

Agora, fazer isso em um código no seu trabalho é péssimo. Obviamente existem pessoas que não sabem, mas precisam ser avisadas, e se continuarem fazendo, não passam de maus profissionais.

Oi,

Apenas um exemplo… quem sabe ajuda:

// Criando um Frame
JFrame
frame = new JFrame();

// Adicionando uma img
frame.setContentPane(this.CreateContentPane());

Método que cria o container e adiciona imagem:

public Container CreateContentPane() {
	        
     // Criação do painel.
     JPanel contentPane = new JPanel(new BorderLayout());
	        
     // Carrega a imagem.
     JDesktopPane
     desktop = new JDesktopPane() {	
			
          Image im = (new ImageIcon("C:\Temp\Lina.jpg")).getImage();			
			
          public void paintComponent(Graphics g) {        
               g.drawImage(im,0,0,this);				
          }
     };

     // Cria o painel OPACO.
     contentPane.setOpaque(true);

     // Adiciona ao JDesktopPane.
     contentPane.add(desktop);

     // Retorna o painel.
     return contentPane;
}

Tchauzin!

Opa!

vlw o exemplo amanha vo tentar usar isso pq hj eu jah naum to pensando mais :?

ateh!