package test;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontFormatException;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test extends JFrame {
Font definiedFont=null;
InputStream is=null;
BufferedInputStream bis=null;
public static void main(String[] args) {
new Test();
}
public Test(){
super("Test font");
JPanel panel=new JPanel();
setContentPane(panel);
panel.setBackground(Color.WHITE);
panel.setLayout(null);
JButton button=new JButton("Hello World");
button.setBounds(0,0,300,70);
button.setBackground(Color.WHITE);
button.setFont(getDefinedFont());
panel.add(button);
close();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(300, 100, 600, 400);
setVisible(true);
}
public Font getDefinedFont(){
if (definiedFont == null) {
try {
is=Test.class.getResourceAsStream("font/abc.ttf");//Class类的一个方法,将本地的资源加载成一个输入流
bis=new BufferedInputStream(is);
definiedFont=Font.createFont(Font.TRUETYPE_FONT,bis);//使用TRUETYPE类型的字体来创建新的字体
definiedFont=definiedFont.deriveFont(30.0f);//复制当前字体对象并应用新的大小来创建一个新的字体
} catch (FontFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return definiedFont;
}
public void close(){
try {
if (null != is){
is.close();
}
if (null != bis) {
bis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}