In Java we can create a Font object as such:
new Font("Helvetica", Font.PLAIN, 12);
My question is how do we get the entire list of font names from Java, for example "Helvetica" which we can use it as one the argument for the Font constructor?
I tried the following, but I can't find "Helvetica" in all of the lists.
GraphicsEnvironment ge;
ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] names = ge.getAvailableFontFamilyNames();
Font[] allFonts = ge.getAllFonts();
for(int x=0; x<names.length; x++)
System.out.println(names[x]);
for(int x=0; x<allFonts.length; x++){
System.out.println(allFonts[x].getName());
System.out.println(allFonts[x].getFontName());
System.out.println(allFonts[x].getFamily());
System.out.println(allFonts[x].getPSName());
}
Edit: More importantly, I also want to know what is the first attribute call in Font constructornew Font("What attribute is this?", Font.PLAIN, 12)
Q: Is it a fontName, family, fontFace, name or what?
Answer: To list all the fonts available to you in a Java application (a Java Swing application), use the GraphicsEnvironment. getLocalGraphicsEnvironment().
Logical fonts are the five font families defined by the Java platform which must be supported by any Java runtime environment: Serif, SansSerif, Monospaced, Dialog, and DialogInput.
You can use the getFamily( ) method to find out the family name, while getFontName( ) returns the face name of the font. Finally, to actually use a Font object, you can simply specify it as an argument to the setFont( ) method of a Component or Graphics object.
setFont(Font f) Set the Font of this object. Constructors in java.awt with parameters of type Font. Constructor and Description.
On your system, that font may well be mapped to something else
Font helvetica = new Font("Helvetica", Font.PLAIN, 12);
System.out.println(helvetica.getFontName(Locale.US));
and I get
SansSerif.plain
To output the names of all local fonts, you could use something like
GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
Font[] allFonts = ge.getAllFonts();
for (Font font : allFonts) {
System.out.println(font.getFontName(Locale.US));
}
new Font("Helvetica", Font.PLAIN, 12);
In this case, it is better to use something like:
new Font(Font.SANS_SERIF, Font.PLAIN, 12);
That will produce the undecorated Font
used by default on that OS.
On Windows it would be Arial. On OS X it would be Helvetica. On *nix machines it might be either, or a 3rd undecorated Font
.
In answer to your specific question, I've always found the 'font family' string to be useful for creating an instance of the font.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With