0

I have a project in JAVA, which has a graphical interface with a screen, developed with Swing.

I have 2 images, background and favicon, which are in the package:

br\com\drsolutions\monitorar\imagens

Project Structure:

br\com\drsolutions\monitorar\imagens
    Fundo.jpg
    icone.png
br\com\drsolutions\monitorar\rede
    TestarIcmp.java
br\com\drsolutions\monitorar\ux
    InterfaceGrafica.java
br\com\drsolutions\monitorar
    Aplicativo.java

In the InterfaceGrafica.java file, I add the images in JFrame as follows:

...
jFrame = new JFrame("Monitorar");
jFrame.setSize(246, 410);
jFrame.setResizable(false);
jFrame.setLayout(null);
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

/* Colocar a imagem no background e o ícone na janela */
try {
    jFrame.setContentPane(new JLabel(new ImageIcon(
            ImageIO.read(new File("src\\br\\com\\drsolutions\\monitorar\\imagens\\Fundo.jpg")))
    ));
    jFrame.setIconImage(new ImageIcon("src\\br\\com\\drsolutions\\monitorar\\imagens\\icone.png")
            .getImage()
    );
} catch (IOException e) {
    return false;
}
...

How can I add images without having to pass the full path this way?

How to make the images work in the JAR file I generate?

Thanks, Diego M. Rodrigues

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    I think you should look at this answer: https://stackoverflow.com/a/8661032/4904569 – Cr4xy Dec 02 '19 at 11:03
  • *"jFrame.setLayout(null);"* 1) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Dec 02 '19 at 11:44
  • .. **2) Application resources will become embedded resources by the time of deployment, so it is wise to start accessing them as if they were, right now. An [tag:embedded-resource] must be accessed by URL rather than file. See the [info. page for embedded resource](http://stackoverflow.com/tags/embedded-resource/info) for how to form the URL.** – Andrew Thompson Dec 02 '19 at 11:44

1 Answers1

0

You are accessing your file through its path on disk before it gets put into a JAR. You need to use a resource loader as explained in: How to read a file from jar in Java?

Lazar Petrovic
  • 537
  • 3
  • 8