Java Swing 使用非本地字体
package reyo; import java.awt.Container; import java.awt.Font; import java.awt.FontFormatException; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.UIManager; public class ReYoFont extends JFrame { private static final long serialVersionUID = 8844899652191928500L; private Font definedFont = null; public ReYoFont() { super("ReYoFontTest"); this.init(); } private void init() { // 添加一些组件 Container container = getContentPane(); setLayout(new BoxLayout(container, BoxLayout.Y_AXIS)); for (float align = 0.0f; align <= 1.0f; align += 0.25f) { JButton button = new JButton("X align = " + align); button.setFont(getDefinedFont()); button.setAlignmentX(align); container.add(button); container.add(Box.createVerticalGlue()); } // 设置窗体属性 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(300, 100, 600, 400); setVisible(true); } public Font getDefinedFont() { if (definedFont == null) { InputStream is = null; BufferedInputStream bis = null; try { is = ReYoFont.class.getResourceAsStream("/reyo.ttf"); bis = new BufferedInputStream(is); // createFont返回一个使用指定字体类型和输入数据的新 Font。<br> // 新 Font磅值为 1,样式为 PLAIN,注意 此方法不会关闭 InputStream definedFont = Font.createFont(Font.TRUETYPE_FONT, bis); // 复制此 Font对象并应用新样式,创建一个指定磅值的新 Font对象。 definedFont = definedFont.deriveFont(30); } catch (FontFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (null != bis) { bis.close(); } if (null != is) { is.close(); } } catch (IOException e) { e.printStackTrace(); } } } return definedFont; } public static void main(String args[]) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { } new ReYoFont(); } }