Reputation: 177
I want to Load an Image and use it as the Back Ground for my JPanel, This Code doesn't give me any errors or results.
I also Tried using BufferedImage and setting the File location to the path of the image, but i got an error "Can't read input file!", After some research i found this method and an easier alternative.
import javax.swing.ImageIcon;
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.io.File;
import java.io.IOException;
public class drawArea extends JPanel {
public drawArea(){
init();
}
private void init(){
setPreferredSize( new Dimension( 570, 570 ) );
setVisible(true);
}
private void initializeGrid(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
Image img = new ImageIcon("/LinearEquations/src/exit.png").getImage();
g2d.drawImage(img, 0, 0, this);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
initializeGrid(g);
}
}
Thanks in Advance
Upvotes: 2
Views: 3941
Reputation: 285440
Never ever read in an image in the paint or paintComponent method. Understand that this method largely determines the perceived responsiveness of your program, and if you slow it down by needlessly repeatedly reading in images, your users won't be happy.
Your problem is likely one of using the wrong relative path. I recommend that you try to read your image in in the init()
method and storing it as a variable. Don't read it in as a File as you're doing but rather as a InputStream obtained from a class resource.
e.g.,
public class DrawArea extends JPanel {
// we've no idea if this is the correct path just yet.
private static final String IMG_PATH = "/exit.png";
public DrawArea() { // better have it throw the proper exceptions!
setPreferredSize( new Dimension( 570, 570 ) ); // not sure about this either
// setVisible(true); // no need for this
img = ImageIO.read(getClass().getResourceAsStream(IMG_PATH));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
g.drawImage(img, 0, 0, this);
}
}
Upvotes: 4