I am learning some lessons and I am having trouble loading a font file in the Eclipse Java Project. I tried many of the solutions offered here on SO and ended up finding one (using FileInputStream) that works for me, but not when the project is exported as a runnable JAR. On the other hand, using the same directory structure in another project where I upload the icons works, so I think the problem is not in the path itself.
Here is the directory structure
:
Here is the code:
package examples; import java.awt.Font; import java.awt.FontFormatException; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URISyntaxException; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; public class Test01 extends JPanel { String text = "Free the bound periodicals"; Font fon; FileInputStream fis;
So what bothers me:
- Why this does not work (it seems he cannot find the font file), since it throws a NullPointerException
fis = this.getClass().getResourceAsStream("/examples/resources/vedrana.ttf");
and does not work
fis = this.getClass().getClassLoader().getResourceAsStream("/examples/resources/verdana.ttf");
- Why does this work in an Eclipse project, but not when exporting to a runnable JAR
fis = new FileInputStream(new File(getClass().getResource("/examples/resources/verdana.ttf").toURI()));
UPDATE As it turned out, this will work:
fis = this.getClass().getClassLoader().getResourceAsStream("examples/resources/verdana.ttf");
The problem was in the first braid - the path should be "examples / resources / verdana.ttf" instead of "/examples/resources/verdana.ttf". It works in both Eclipse and the runnable JAR.
Now what intrigues me is that in this case the first slash is needed
ImageIcon loadIcon = new ImageIcon(getClass().getResource("/examples/resources/load.gif"));
UPDATE 2 : After disappointment, why this method does not work.
InputStream fis = this.getClass().getResourceAsStream("/examples/resources/verdana.ttf");
I removed the entire class from Eclipse and now the BOTH methods work in the Eclipse and runanble JAR - as it should be.
InputStream fis = this.getClass().getResourceAsStream("/examples/resources/verdana.ttf");
or
InputStream fis = this.getClass().getClassLoader().getResourceAsStream("examples/resources/verdana.ttf");