I am a bit new at Java and Netbeans but I've heard that you are a great and helpful community, so could you give me an advice how is it possible that a source code (after compiled) works fine if I hit the green triangle in NetBeans, but if I open the contain of the DIST/jar file (outside from NetBeans) it is not?
More precisely the application runs well but one specific function doesn't run when I click a button (PDF generation with iText plugin).
Here is a part of code of the not working method (as I mentioned the button works, but only if I start my App from NetBeans)
If I remove the image reference, the Application runs well from outside (total commander, /dist/myapp.jar, Enter), but I really would like to use the image in the PDF file. The path is good (since it is working from netbeans)
So I am 100% sure that the .jar does not find the logo (if it works without it,) but then how could it find if it is started from NetBeans? What could I rewrite at the path? (I tried "/", "@", "/src" while the .png can be found at /src just like the other pictures (which are loaded perfectly) )
public void pdfGenerate(String title, String text) {
............................
document.open();
Image image1 = Image.getInstance("src/logo.png");
image1.scaleToFit(200, 86);
image1.setAbsolutePosition(200f, 750f);
document.add(image1);
document.add(new Paragraph("\n\n\n\n\n" + text, FontFactory.getFont("font", BaseFont.IDENTITY_H, BaseFont.EMBEDDED)));
} catch (Exception e) {
e.printStackTrace();
}
document.close();
...............................
}
When you package your application as a jar file, the resources should be packaged there too. The method you are calling interprets the string as a filename; that file will not be present on the system when the jar file is created and deployed.
What you need to do is specify a URL for the resource. You can do this using getClass().getResource(...)
. If you specify a resource path here starting /
, it will be interpreted relative to the classpath; otherwise it is relative to the current class.
Note that there is an overloaded form of Image.getInstance(...)
taking a URL.
So, it looks like you need
Image image1 = Image.getInstance(getClass().getResource("/logo.png"));
You can also check the contents of the jar file from the command line with
jar -tf yourfile.jar
to make sure the image file is in there.