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

 

转载于:https://www.cnblogs.com/interdrp/p/5034270.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值