mahadi_mohammad
mahadi_mohammad

Reputation: 161

Do not want to keep image outside of jar file in same folder

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

Answers (2)

mahadi_mohammad
mahadi_mohammad

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

Maxim
Maxim

Reputation: 9961

You can just store images inside JAR as resources. This tutorial explains how to do it. When you read it I think you can adopt it for your build system (Maven, Gradle, etc.).

Upvotes: 1

Related Questions