import sun.font.Font2DHandle; //导入依赖的package包/类
/**
* Returns a new Font
using the specified font type
* and the specified font file. The new Font
is
* created with a point size of 1 and style {@link #PLAIN PLAIN}.
* This base font can then be used with the deriveFont
* methods in this class to derive new Font
objects with
* varying sizes, styles, transforms and font features.
* @param fontFormat the type of the Font
, which is
* {@link #TRUETYPE_FONT TRUETYPE_FONT} if a TrueType resource is
* specified or {@link #TYPE1_FONT TYPE1_FONT} if a Type 1 resource is
* specified.
* So long as the returned font, or its derived fonts are referenced
* the implementation may continue to access fontFile
* to retrieve font data. Thus the results are undefined if the file
* is changed, or becomes inaccessible.
*
* To make the Font
available to Font constructors the
* returned Font
must be registered in the
* GraphicsEnviroment
by calling
* {@link GraphicsEnvironment#registerFont(Font) registerFont(Font)}.
* @param fontFile a File
object representing the
* input data for the font.
* @return a new Font
created with the specified font type.
* @throws IllegalArgumentException if fontFormat
is not
* TRUETYPE_FONT
orTYPE1_FONT
.
* @throws NullPointerException if fontFile
is null.
* @throws IOException if the fontFile
cannot be read.
* @throws FontFormatException if fontFile
does
* not contain the required font tables for the specified format.
* @throws SecurityException if the executing code does not have
* permission to read from the file.
* @see GraphicsEnvironment#registerFont(Font)
* @since 1.5
*/
public static Font createFont(int fontFormat, File fontFile)
throws java.awt.FontFormatException, java.io.IOException {
fontFile = new File(fontFile.getPath());
if (fontFormat != Font.TRUETYPE_FONT &&
fontFormat != Font.TYPE1_FONT) {
throw new IllegalArgumentException ("font format not recognized");
}
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
FilePermission filePermission =
new FilePermission(fontFile.getPath(), "read");
sm.checkPermission(filePermission);
}
if (!fontFile.canRead()) {
throw new IOException("Can't read " + fontFile);
}
// create a private Font Collection and add the font data
PrivateFontCollection pfc = new PrivateFontCollection();
try {
String fileName = fontFile.getPath();
pfc.AddFontFile( fileName );
RemoveFontResourceEx( fileName );// hack for bug http://stackoverflow.com/questions/26671026/how-to-delete-the-file-of-a-privatefontcollection-addfontfile
if (false) throw new cli.System.IO.FileNotFoundException();
} catch( cli.System.IO.FileNotFoundException fnfe ) {
FileNotFoundException ex = new FileNotFoundException(fnfe.getMessage());
ex.initCause( fnfe );
throw ex;
}
// create the font object
Font2D font2D = SunFontManager.createFont2D( pfc.get_Families()[0], 0 );
Font2DHandle font2DHandle = font2D.handle;
Font font = new Font( font2D.getFontName( Locale.getDefault() ), PLAIN, 1, true, font2DHandle );
return font;
}