1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 package ca.uhn.hl7v2.testpanel.util;
27
28 import java.awt.Font;
29 import java.awt.FontMetrics;
30 import java.awt.Graphics;
31 import java.awt.GraphicsEnvironment;
32 import java.awt.image.BufferedImage;
33 import java.util.ArrayList;
34 import java.util.Collections;
35 import java.util.List;
36
37 public class FontUtil {
38
39
40
41
42 public static List<String> getMonospacedFontNames() {
43
44 List<String> monospaceFontFamilyNames = new ArrayList<String>();
45
46 GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
47 String[] fontFamilyNames = graphicsEnvironment.getAvailableFontFamilyNames();
48
49 BufferedImage bufferedImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
50 Graphics graphics = bufferedImage.createGraphics();
51
52 for (String fontFamilyName : fontFamilyNames) {
53 boolean isMonospaced = true;
54
55 int fontStyle = Font.PLAIN;
56 int fontSize = 12;
57 Font font = new Font(fontFamilyName, fontStyle, fontSize);
58 FontMetrics fontMetrics = graphics.getFontMetrics(font);
59
60 int firstCharacterWidth = 0;
61 boolean hasFirstCharacterWidth = false;
62 for (int codePoint = 0; codePoint < 128; codePoint++) {
63 if (Character.isValidCodePoint(codePoint) && (Character.isLetter(codePoint) || Character.isDigit(codePoint))) {
64 char character = (char) codePoint;
65 int characterWidth = fontMetrics.charWidth(character);
66 if (hasFirstCharacterWidth) {
67 if (characterWidth != firstCharacterWidth) {
68 isMonospaced = false;
69 break;
70 }
71 } else {
72 firstCharacterWidth = characterWidth;
73 hasFirstCharacterWidth = true;
74 }
75 }
76 }
77
78 if (isMonospaced) {
79 monospaceFontFamilyNames.add(fontFamilyName);
80 }
81 }
82
83 graphics.dispose();
84
85 Collections.sort(monospaceFontFamilyNames);
86 return monospaceFontFamilyNames;
87
88 }
89
90 }