Como hago para ponerle una imagen de fondo a un JFrame? He visto algunos ejemplos pero usan un código muy extenso...
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GuiTestBed extends JPanel
{
private static final long serialVersionUID = 1L;
public static void main(String args[])
{
JFrame frame = new JFrame("GUI Test Bed 2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setSize(765,503);
frame.getContentPane().setBackground(Color.BLUE);
String path = "direccion de tu imagen";
JLabel myLabel = new JLabel();
try
{
URL url = new URL(path);
BufferedImage image = ImageIO.read(url);
myLabel = new JLabel(new ImageIcon(image));
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
frame.getContentPane().add(myLabel);
//frame.getContentPane().add(new GuiTestBed());
frame.setVisible(true);
}
public void paint(Graphics g)
{
g.setColor(Color.WHITE);
g.setFont(new Font("Comic Sans Ms", Font.BOLD, 14));
g.drawString("Timer: 1:04:32" , 550, 260);
g.drawString("Edu XP : 22223" , 550, 280);
}
}
Mira, yo uso una imagen del tamaño del frame.
Por ejemplo hago un dibujito en tuxPaint (Es como el "paint" de window$) y lo guardo al tamaño que necesito.
Entonces:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ImagenFondo extends JPanel{
// imagen de fondo
private ImageIcon fondo;
// frame donde va este panel
JFrame frame = new JFrame("Imagen de fondo");
public ImagenFondo(){
// cerrar por defecto, tamanio, visibilidad...
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setVisible(true);
frame.add(this); // agrego este mismo panel
// creo el fondo con la ruta de la imagen
fondo = new ImageIcon("img_fondo-PC.png");
// coloco la imagen y le envio las graficas y la posicion
fondo.paintIcon(null, getGraphics(), 0, 0);
}
public void paint(Graphics g){
//pongo un color fondo (no sirve para nada si esta la imagen sobre el)
g.setColor(Color.black);
g.fillRect(0, 0, 400, 400);
//cuando no sale el fondo lo coloco aqui (fondo.paintIcon(null, g, 0, 0);)
}
public static void main(String[] args){
new ImagenFondo();
}
}
PD: la imgagen que tengo "img_fondo-PC.png" mide 400x400 y la tengo dentro del proyecto fuera de la carpetas "src" y "bin"