12. 字体:
1) 通过之前介绍的图形环境(GraphicsEnvironment)工具类获取当前系统支持的所有字体。
1 public class MyTest {
2 public static void main(String[] args) {
3 String[] fontFamilies = GraphicsEnvironment.getLocalGraphicsEnvironment()
4 .getAvailableFontFamilyNames();
5 for (String fn : fontFamilies)
6 System.out.println(fn);
7 Font[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
8 for (Font f : fonts) {
9 System.out.print(f.getFontName() + " : ");
10 System.out.print(f.getFamily() + " : ");
11 System.out.print(f.getName());
12 System.out.println();
13 }
14 }
15 }
2) 动态加载TTF字体文件。
该示例同时加载了一种字体的两种形式:正常和粗体,以便于观察渲染后的结果。
1 public class MyTest extends JPanel {
2 private Font font;
3 private Font boldFont;
4
5 MyTest() {
6 InputStream fin = null;
7 InputStream finBold = null;
8 try {
9 fin = new FileInputStream("D:/arial.ttf");
10 finBold = new FileInputStream("D:/arialbd.ttf");
11 font = Font.createFont(Font.TRUETYPE_FONT, fin).deriveFont(50.0f);
12 boldFont = Font.createFont(Font.TRUETYPE_FONT, finBold).deriveFont(50.0f);
13 } catch (Exception e) {
14 } finally {
15 try {
16 fin.close();
17 finBold.close();
18 } catch (IOException e) {
19 }
20 }
21 }
22 public void paintComponent(Graphics g) {
23 super.paintComponent(g);
24 Graphics2D g2 = (Graphics2D) g;
25 g2.setFont(font);
26 g2.drawString("Normal Hello", 100, 100);
27 g2.setFont(boldFont);
28 g2.drawString("Bold Hello", 100, 300);
29 }
30 public static void main(String[] args) {
31 JFrame frame = new JFrame();
32 frame.setTitle("Load TTF From File");
33 frame.addWindowListener(new WindowAdapter() {
34 public void windowClosing(WindowEvent e) {
35 System.exit(0);
36 }
37 });
38 frame.setContentPane(new MyTest());
39 frame.setSize(600, 400);
40 frame.setVisible(true);
41 }
42 }
3) 绘制指定字体的文本信息:
在我们的日常开发中,基于文本信息的应用更多的是输出日志、给出提示信息和填充字符类型的数据库字段等,即便是在Swing的控件中显示这些文字提示时, 也是通过控件提供的属性修改器方法来协助完成的。那么Swing的控件又是如何做到的呢?试想一下,JButton上的文字是如何绘制的?
1 public class MyTest extends JPanel {
2 public static void main(String args[]) {
3 JFrame f = new JFrame("Strings");
4 f.setSize(360, 300);
5 f.add(new MyTest());
6 f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
7 f.setLocationRelativeTo(null);
8 f.setVisible(true);
9 }
10 public MyTest() {
11 setBackground(Color.white);
12 setForeground(Color.white);
13 }
14 @Override
15 public