Font.createFont(..) set color and size (java.awt.Font)

konze picture konze · May 26, 2013 · Viewed 144.1k times · Source

I'd like to create a new Font object using a TTF file. It is really simple to create a Font object but I don't know how to set color and size because I can't find a method for it?

InputStream is = new FileInputStream("helvetica.ttf");
Font helvetica = Font.createFont(Font.TRUETYPE_FONT, is);

Answer

Erik Pragt picture Erik Pragt · May 26, 2013

Font's don't have a color; only when using the font you can set the color of the component. For example, when using a JTextArea:

JTextArea txt = new JTextArea();
Font font = new Font("Verdana", Font.BOLD, 12);
txt.setFont(font);
txt.setForeground(Color.BLUE);

According to this link, the createFont() method creates a new Font object with a point size of 1 and style PLAIN. So, if you want to increase the size of the Font, you need to do this:

 Font font = Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf"));
 return font.deriveFont(12f);