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 !
Darkness
July 31, 2009, July 31, 2009 14:55, permalink
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")));
Marcos Vasconcelos
September 30, 2009, September 30, 2009 16:33, permalink
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();
}
}
Do you know how I can apply a background image to a JFrame?