Custom font setup

I am trying to set my own font (bilboregular.ttf) to 2 jLabels in my program. Fonts do not load successfully, though.

Here is the main method call:

//this should work if the build is in a jar file, otherwise it'll try to load it directly from the file path (i'm running in netbeans) if (!setFonts("resources/bilboregular.ttf")) { System.out.println("=================FAILED FIRST OPTION"); // <<<<<<<< This is being displayed if(!setFonts(System.getProperty("user.dir")+"/src/resources/bilboregular.ttf")){ System.out.println("=================FAILED SECOND OPTION"); // <<< This is not being displayed } } 

Here is another way:

 public boolean setFonts(String s) { try { jLabel3.setFont(java.awt.Font.createFont(java.awt.Font.TRUETYPE_FONT, new java.io.File(s))); jLabel4.setFont(java.awt.Font.createFont(java.awt.Font.TRUETYPE_FONT, new java.io.File(s))); return true; } catch (Exception ex) { return false; } } 
+4
source share
2 answers

First get the URL in Font . Then do something like that.

'Airacobra Condensed' font is available from Free Fonts Download .

Registered Font

 import java.awt.*; import javax.swing.*; import java.net.URL; class LoadFont { public static void main(String[] args) throws Exception { // This font is < 35Kb. URL fontUrl = new URL("http://www.webpagepublicity.com/" + "free-fonts/a/Airacobra%20Condensed.ttf"); Font font = Font.createFont(Font.TRUETYPE_FONT, fontUrl.openStream()); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); ge.registerFont(font); JList fonts = new JList( ge.getAvailableFontFamilyNames() ); JOptionPane.showMessageDialog(null, new JScrollPane(fonts)); } } 

Well, that was fun, but what does this font look like?

Display font

 import java.awt.*; import javax.swing.*; import java.net.URL; class DisplayFont { public static void main(String[] args) throws Exception { URL fontUrl = new URL("http://www.webpagepublicity.com/" + "free-fonts/a/Airacobra%20Condensed.ttf"); Font font = Font.createFont(Font.TRUETYPE_FONT, fontUrl.openStream()); font = font.deriveFont(Font.PLAIN,20); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); ge.registerFont(font); JLabel l = new JLabel( "The quick brown fox jumped over the lazy dog. 0123456789"); l.setFont(font); JOptionPane.showMessageDialog(null, l); } } 
+11
source
  • do not reload the new Font , for each of JLabel separatelly

means

 public boolean setFonts(String s) { try { jLabel3.setFont(java.awt.Font.createFont(java.awt.Font.TRUETYPE_FONT, new java.io.File(s))); jLabel4.setFont(java.awt.Font.createFont(java.awt.Font.TRUETYPE_FONT, new java.io.File(s))); return true; } catch (Exception ex) { return false; } } 

eg

 InputStream myFont = OptionsValues.class.getResourceAsStream( "resources/bilboregular.ttf"); 
+5
source

All Articles