Reputation: 161
public void paintComponent(Graphics g) {
Image frstWinBackg = new ImageIcon("new.jpg").getImage();
g.drawImage(frstWinBackg, 0, 0, getWidth(), getHeight(), this);
}
I am drawing an image file as JPanel background through above code. When I make executable jar file of my project, I have to keep that image file in same folder. Is there any way to compact this image file inside jar file as I think providing image file along with jar file is not a good idea.
Upvotes: 0
Views: 62
Reputation: 161
public void paintComponent(Graphics g) {
Image frstWinBackg = new ImageIcon("new.jpg").getImage();
g.drawImage(frstWinBackg, 0, 0, getWidth(), getHeight(), this);
}
In this code, image file is read inside paintComponent() method. As paintComponent() method can be called several times in a second, it searches for image file every time. So, to make appearing the image, image file has to be kept in the same folder of jar file.
If we don't want to provide image file externally, we must read image inside the constructor and draw it by paintComponent() method.
e.g. In constructor, to read image file:
Image img = ImageIO.read(getClass().getResource("resources/new.jpg"));
Then, paintComponent() method will be:
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
g.drawImage(img, 0, 0, this);
}
Upvotes: 2