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();
	}
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM