JPanel dúvidas

Como faço para colocar um figura como plano de fundo no JPanel???

tem que colocar um LABEL e nesse label vc coloca a figura :wink:

Apenas pesquisando no fórum pelas palavras chave fundo JPanel encontrei o seguinte tópico

renzonuccitelli ta certo seria bom da uma pesquisada antes de postar a duvida…mas K pra nos…tem muito topico que as pessoas abrem com os titulos que nao tem nada haver…

ex:

consultar não está dando certo …

esse topico é sobre rms J2ME…

Oi,

sua resposta já foi dita por abelgomes.

Basta criar um label e nele receber um Icone, logo após adicione seu label ao painel.

Tchauzin

abelgomes, concordo com vc. Mas nesse caso, eu apenas coloqueis as palavras chave e achei resposta. Por isso antes de colocar questões, eu dou uma procurada no fórum, só criando um post novo quando não encontro nada, já que ficar criando vários posts sobre as mesmas coisas polui todo o forum. E ainda sei que tem muita gente que simplesmente nem se dá ao trabalho de procurar, já que é mais fácil apenas perguntar…

Ainda sobre o assunto do tópico, se desejar que a imagem fico como pano de fundo, ou seja, que quando componentes forem adicionados no frame isso não altere a imagem, a solução via JLabel não vai funcionar, já que o Layout vai alterar a posição do Label.

depende pra e como ele quer essa img…minha ideia foi essa

[quote=renzonuccitelli] abelgomes, concordo com vc. Mas nesse caso, eu apenas coloqueis as palavras chave e achei resposta. Por isso antes de colocar questões, eu dou uma procurada no fórum, só criando um post novo quando não encontro nada, já que ficar criando vários posts sobre as mesmas coisas polui todo o forum. E ainda sei que tem muita gente que simplesmente nem se dá ao trabalho de procurar, já que é mais fácil apenas perguntar…

Ainda sobre o assunto do tópico, se desejar que a imagem fico como pano de fundo, ou seja, que quando componentes forem adicionados no frame isso não altere a imagem, a solução via JLabel não vai funcionar, já que o Layout vai alterar a posição do Label.[/quote]

Só que eu to usando um frameview como form principal e o label em cima do panel não funcionou, aconteceu justamente o que você falou, mas embora voce já chegue dizendo q achou “as respostas”, as que voce respondeu com o link lá em cima não chegou nem perto de responder a minha dúvida, então minha dúvida permanece e espero que alguem possa me responder com clareza, ok?
Obrigado pela ajuda as pessoas que realmente se disponibilizaram a tentar ajudar

Seguinte…

Estava com o mesmo problema…

crie uma instacia desta classe em seu projeto principal

Classe: >>>

[code]
import java.awt.Graphics;
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 background = null;
    private FillType fillType = FillType.CENTER;

    /** 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();
    }

    /**

    • Returns the way this image fills itself.
    • @return The fill type.
      */
      public FillType getFillType()
      {
      return fillType;
      }

    /**

    • 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);    
    

    }
    }[/code]

Esta classe foi postada pelo Vinigod0y à algum tempo atras…

neste tópico: http://www.guj.com.br/posts/list/56248.java#295271

Declare como váriavel de classe um instância de JImagePanel ex: (JImagePanel imagem = new JImagePanel(); )

depois crie um método set, ex:

private void setImg(String caminhoDaImagem) {  
           try {
               imagem = new JImagePanel(caminhoDaImagem);                 
           } catch (Exception ex) {  
               ex.printStackTrace();  
           }   
                imagem.setBounds(5,15,196,320);  
                jPanel.removeAll(); //jPanel é o seu JPanel mostrado na tela... no qual vai receber a imagem
                jPanel.add(JPi);  
                jPanel.repaint();  
           }

i pronto…

Espero ter ajudado… um abraço!

Bom, quando eu precisei de coisa parecida, eu encontrei pela net e adaptei o seguinte código:

[code]public class Desktop extends JDesktopPane {
public void paintComponent(Graphics graphics) {
ImageIcon leBaroneIcon= new ImageIcon(getClass().getResource(“diamanteBranco.jpg”));
super.paintComponent(graphics);

	// Desenha a imagem e a centraliza no componente.
	graphics.drawImage(leBaroneIcon.getImage(),getX(leBaroneIcon.getIconWidth()),getY(leBaroneIcon.getIconWidth()),this.getBackground(), this);
} 

private int getX(int width){
	if(this.getWidth()-width>0)
		return (this.getWidth()-width)/2;
	else 
		return 0;
}

private int getY(int height){
	if(this.getHeight()-height>0)
		return (this.getHeight()-height)/2;
	else 
		return 0;
}

}
[/code]

Esse código deixa o logo da empresa sempre centralizado e basta utilizar instancias dessa classe em vez de JDesktopPane. Vc pode usar o código tb para o JPanel…

Só pra constar, a classe que o DorPho postou foi o ViniGodoy que fez a um tempo e postou aqui no fórum.

lina… faz tempo que não vejo voce falando algo aqui.^^

Valeu por tudo…
Muito obrigado mesmo
problema resolvido :smiley:

Bem que eu estava sentido falta de algo… você eliminou os métodos setImage!

Eis a classe original:

[code]import java.awt.Graphics;
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;
      }

    @Override
    protected void paintComponent(Graphics g)
    {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g.create();
    fillType.drawImage(this, g2d, image);
    g2d.dispose();
    }

    /**

    • Returns the way this image fills itself.
    • @return The fill type.
      */
      public FillType getFillType()
      {
      return fillType;
      }

    /**

    • 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);
    

    }
    }[/code]

Para trocar a imagem, não é necessário criar um JImagePanel novo. Nem trocar o conteúdo de nenhum painel.
É só chamar:

Não faça como o amigo sugeriu no método setImg. O código dele contém um erro: sempre que você troca algum componente de um JPanel, é necessário chamar o método invalidate(), não repaint(). Além disso, não tem porque substituir o painel inteiro, se você pode trocar só a imagem dentro dele.

Outra coisa, o Linkel postou aqui no GUJ uma versão da JImagePanel contendo duas opções a mais de pintura. Elas deixam a imagem centralizada no painel e mantém suas proporções. Talvez fosse interessante vocês procurarem pelo link dela.

[quote=Mark_Ameba]Só pra constar, a classe que o DorPho postou foi o ViniGodoy que fez a um tempo e postou aqui no fórum.

[/quote]

Eu não deixei de citar isso amigo… é só ler o post completo!
Um abraço!

Sorry até eu postar não tinha visto nada.