3f9f2d31e0d42bc91d3135953eb41d2e

Do you know how I can apply a background image to a JFrame?

Image background;

try {
background = ImageIO.read(new File("PATH"));	}
catch (IOException e) { e.printStackTrace(); }
paintComponent(background)

// then I try to create a method paintComponent
public void paintComponent(Graphics g) {
    	super.paintComponents(g);
    	if (background == null) return;
    	
    	//draw the image in the upper-left corner
    	g.drawImage(background, 0, 0, null);
    }
// but I had errors on casting from Image to Graphics

Refactorings

No refactoring yet !

D41d8cd98f00b204e9800998ecf8427e

Darkness

July 31, 2009, July 31, 2009 14:55, permalink

No rating. Login to rate!

I'm not sure if it's valid to lay an image over a JFrame. It might be, but
a more straight foward approach might be to place a JLabel with no text
over the Frame, with code like the following.

JLabel SomeLabel = new javax.swing.JLabel();
SomeLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("YourImagePathHere.jpg")));
8a3f52058098379cd556f98d5f3aa38b

Marcos Vasconcelos

September 30, 2009, September 30, 2009 16:33, permalink

No rating. Login to rate!

The correct is override paintComponent methodfrom a JPanel.

public class JImagePanel extends JPanel {
BufferedImage img;
public JImagePanel(){
try{
 img = ImageIO.read(new File("path/arq.ext");
}catch(Exception e){/*do propper handling */}
}
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.drawImage(img,0,0,img.getWidth(),img.getHeight(),this);
g2d.dispose();
}
}

Your refactoring





Format Copy from initial code

or Cancel