2023年12月14日发(作者:)

[JAVA]java_实例获得系统字体

这个代码可以帮助理解java是如何获取系统字体并设置文字字体:

1 import .*;

2 import .*;

3

4 import Box;

5 import ;

6 import ;

7

8 public class GetSystemFont extends JFrame {

9

10 private JComboBox box;

11 private Container container;

12 private String str[];

13 private GraphicsEnvironment environment; // 该类中又获取系统字体的方法;

14 private JLabel tipLabel;

15

16 public GetSystemFont() {

17 super("获取系统字体");

18 container = getContentPane();

19 tipLabel = new JLabel("系统字体有:");

20 (tipLabel);

21

22 environment = alGraphicsEnvironment();// GraphicsEnvironment是一个抽象类,不能实例化,只能用其中的静态方法获取一个实例

23 str = ilableFontFamilyNames();// 获取系统字体

24

25 box = new JComboBox(str);

26

27 // 为box注册ItemListener监听器

28 mListener(new ItemListener() {

29 public void itemStateChanged(ItemEvent event) {

30 if (teChange() == ED) {

31 int style = t().getStyle(); // 获取当前字体的类型

32 int size = t().getSize();// 获取当前字体的大小

33 t(new Font(str[ectedIndex()],

34 style, size));// 改变tipLabel的字体,但不改变大小和类型

35 }

36 }

37 });

38

39 out(new FlowLayout());

40 (box);

41

42 setDefaultCloseOperation(_ON_CLOSE);

43 setVisible(true);

44 pack();

45 setResizable(false);

46

47 // 使窗口屏幕居中

48 Toolkit kit = aultToolkit();// 抽象类,通过静态方法获取实例

49 Dimension frameSize = new Dimension(), screenSize = eenSize(); // 获取屏幕的大小

50 getSize(frameSize); // 获取窗口大小

51 setLocation(( - ) / 2,

52 ( - ) / 2);

53 }

54

55 public static void main(String[] args) {

56 GetSystemFont test = new GetSystemFont();

57 }

58 }