Swing组件可以自定义的字体,做成jar文件之后也可以使用。只需程序加载的时候读取自带的字体,然后在程序中调用此字体就好了。下面的程序组件布局采用的是BoxLayout布局管理器。程序效果图如下:
代码如下:
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;
/**
*
* @author Alog2012
*
*/
@SuppressWarnings("serial")
public class FontTest extends JFrame {
private Font definedFont = null;
public FontTest() {
super("FontTest --by Alog2012");
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 = FontTest.class.getResourceAsStream("/font/abc.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 FontTest();
}
}