package chapter1;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
public class FontDemo extends JPanel {
private static final long serialVersionUID = 1L;
public FontDemo(){
super();
}
public void paintComponent(Graphics g){
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setPaint(Color.BLUE);
try {
g2d.setFont(loadFont());
} catch (IOException e) {
e.printStackTrace();
} catch (FontFormatException e) {
e.printStackTrace();
}
g2d.drawString("Font Demo",50,50);
g2d.dispose();
}
public Font loadFont() throws IOException, FontFormatException {
String fontfilename = "AMERSN.ttf";
InputStream is = this.getClass().getResourceAsStream(fontfilename);
Font actionJson = Font.createFont(Font.TRUETYPE_FONT,is);//返回一个指定字体类型和输入数据的font
Font actionJsonBase = actionJson.deriveFont(Font.BOLD,16);//通过复制此 Font 对象并应用新样式和大小,创建一个新 Font 对象。
return actionJsonBase;
}
public static void main(String args[]){
JFrame ui = new JFrame("Font Demo Graphics2D");
ui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ui.getContentPane().setLayout(new BorderLayout());
ui.getContentPane().add(new FontDemo(),BorderLayout.CENTER);
ui.setPreferredSize(new Dimension(380,380));//设置最好的大小,根据界面的调整大小跟着变化
ui.pack();
ui.setVisible(true);
}
}