debug_mode=ON

Buscar en

 
 

JPanel con imagen de fondo

Escrito por fabnun hace 1 años bajo Dominio Público
7588 visitas. Etiquetas: java, jpanel, swing

El siguiente código presenta una clase que extiende de JPanel y tiene la gracia que al ser dibujada pinta una imagen de fondo mediante el método setBackground(File o URL).

Básicamente lo que se hace es redefinir el método paint, primero pintando con el color de fondo seleccionado, luego pintando la imagen y finalmente pintando todos los componentes que agreguemos al panel.

A parte lo explicado funciona como cualquier otro JPanel.

 import java.awt.*;
 import java.io.*;
 import java.net.URL;
 import javax.imageio.ImageIO;
 import javax.swing.JPanel;

 public class JPanelBackground extends JPanel {
 private static final long serialVersionUID = -3488034684833395929L;

    Image imagen=null;

    public void setBackground(File file) throws IOException{
        if (file==null)
            imagen=null;
        else
            imagen=ImageIO.read(file);
    }

    public void setBackground(URL url) throws IOException{
        if (url==null)
            imagen=null;
        else
            imagen=ImageIO.read(url);
    }

    @Override
    public void paint(Graphics g) {
        g.setColor(getBackground());
        g.fillRect(0,0,getWidth(),getHeight());
        if (imagen!=null)
            g.drawImage(imagen, 0, 0, null);
        Component c;
        for (int i = 0; i < getComponentCount(); i++) {
            c = getComponent(i);
            g.translate(c.getX(), c.getY());
            c.print(g);
            g.translate(-c.getX(), -c.getY());
        }
    }        
 }

Ejemplo de uso:

    JFrame frame = new JFrame();
    JPanelBackground background=new JPanelBackground();
    background.setBackground(new File("foto.jpg"));
    frame.setLayout(new BorderLayout());
    background.add(new JButton("boton"));
    frame.add(background, BorderLayout.CENTER);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);

Saludos.

 

¡Votalo! 2 votos
¡Compártelo!

        

&nbps;

&nbps;

fabnun

Sobre fabnun

Este usuario no ha completado su perfil.

 
Regístrate o haz login para participar.
¿Todavía no conoces debugmodeon?
debugmodeon es la red social para profesionales de la informática
descubre debugmodeon
 

4 comentarios en "JPanel con imagen de fondo"

Vgimeno
Vgimeno escribió
hace 1 años

#1   

Buenas, hace poco volví a trabajar con swing y me encontré con el mismo problema, mire por un par de sitios (siento no tener los enlaces) y la solución que propones no es la mejor de las que encontré, puesto que tienes que pintar tu a mano los componentes que están incluidos en el propio panel, te digo memoria, había que sobrescribir el método paintComponent, no el paint normal, y así te evitas tener que rederizar tu los componentes.

Mañana cuando vaya a la oficina si me acuerdo te posteo el código.

Un saludo,
Victor

 

fabnun
fabnun escribió
hace 1 años

#2   

Vale, lo acabo de probar y funciona de maravilla.

Gracias y saludos.

 

Vgimeno
Vgimeno escribió
hace 1 años

#3   

Lo prometido es deuda te posteo el codigo de la clase tal cual me quedó, repito que no soy el autor del metodo painComponent y no recuerdo donde lo vi pero va de lujo.

/**
 * Panel con imagen de fondo
 * @author Victor Gimeno 
 */

public class BackgroundImagePanel extends JPanel{

    public static int NO_REPEAT = 0;
    public static int REPEAT_BOTH = 1;
    public static int REPEAT_X = 2;
    public static int REPEAT_Y = 3;

    private Icon imgFondo;

    private int repeat;

    public BackgroundImagePanel() {
        preInit();
    }

    private void preInit(){
        imgFondo = new ImageIcon( getClass().getResource("/es/sgv/sanleg/texturas/papel/textura3.png") );
        repeat = NO_REPEAT;
    }

    public Icon getImgFondo() {
        return imgFondo;
    }

    public void setImgFondo(Icon imgFondo) {
        this.imgFondo = imgFondo;
    }

    public int getRepeat() {
        return repeat;
    }

    public void setRepeat(int repeat) {
        this.repeat = repeat;
    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

            if (imgFondo != null)
            {
                Graphics2D g2 = (Graphics2D)g.create();
                Insets inset = this.getInsets();

                Rectangle clippingRegion = new Rectangle(this.getWidth() - (inset.left + inset.right), this.getHeight() - (inset.top + inset.bottom));

                Rectangle clip = g.getClipBounds();

                int height = getSize().height - inset.bottom;
                int width = getSize().width - inset.right;

                if (clip.y + clip.height > height)
                    clip.height = height - clip.y;

                if (clip.x + clip.width > width)
                    clip.width = width - clip.x;

                g2.setClip(clip);

                int xRepeat = 0;
                int yRepeat = 0;

                if (repeat == REPEAT_BOTH || repeat == REPEAT_Y )
                    yRepeat = (int)Math.ceil(clippingRegion.getHeight() / imgFondo.getIconHeight());

                if (repeat == REPEAT_BOTH || repeat == REPEAT_X )
                    xRepeat = (int)Math.ceil(clippingRegion.getWidth() / imgFondo.getIconWidth());

                for (int i = 0; i <= yRepeat; i++)
                {
                    for (int j = 0; j <= xRepeat; j++)
                    {
                        imgFondo.paintIcon(this, g2, j * imgFondo.getIconWidth() + inset.left, i * imgFondo.getIconHeight() + inset.top);
                    }
                }

                g2.dispose();
            }
    }}

Editado 1 veces. La última vez hace hace 1 años.

 

plunchete
plunchete escribió
hace 1 años

#4   

Siempre que se crea un compoenente en Swing es más adecuado sobreescribir el método paintComponent, de hecho si lo has probado y funciona bien podrías editar el artículo :)

Saludos

 
 
 
 

© Copyright 2008-2009 debug_mode=ON | Aviso legal | Contacto | FAQ | ¿Quiénes somos? |