code_junkie

SWT - OS agnostic way to get monospaced font

Nov 11th, 2011
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. Font mono = new Font(parent.getDisplay(), "Mono", 10, SWT.NONE);
  2.  
  3. private static Font loadMonospacedFont(Display display) {
  4. String jreHome = System.getProperty("java.home");
  5. File file = new File(jreHome, "/lib/fonts/LucidaTypewriterRegular.ttf");
  6. if (!file.exists()) {
  7. throw new IllegalStateException(file.toString());
  8. }
  9. if (!display.loadFont(file.toString())) {
  10. throw new IllegalStateException(file.toString());
  11. }
  12. final Font font = new Font(display, "Lucida Sans Typewriter", 10,
  13. SWT.NORMAL);
  14. display.addListener(SWT.Dispose, new Listener() {
  15. public void handleEvent(Event event) {
  16. font.dispose();
  17. }
  18. });
  19. return font;
  20. }
  21.  
  22. public class Monotest {
  23.  
  24. private static boolean isMonospace(GC gc) {
  25. final String wide = "wgh8";
  26. final String narrow = "1l;.";
  27. assert wide.length() == narrow.length();
  28. return gc.textExtent(wide).x == gc.textExtent(narrow).x;
  29. }
  30.  
  31. private static void testFont(Display display, Font font) {
  32. Image image = new Image(display, 100, 100);
  33. try {
  34. GC gc = new GC(image);
  35. try {
  36. gc.setFont(font);
  37. System.out.println(isMonospace(gc) + "t"
  38. + font.getFontData()[0].getName());
  39. } finally {
  40. gc.dispose();
  41. }
  42. } finally {
  43. image.dispose();
  44. }
  45. }
  46.  
  47. private static void walkFonts(Display display) {
  48. final boolean scalable = true;
  49. for (FontData fontData : display.getFontList(null, scalable)) {
  50. Font font = new Font(display, fontData);
  51. try {
  52. testFont(display, font);
  53. } finally {
  54. font.dispose();
  55. }
  56. }
  57. }
  58.  
  59. public static void main(String[] args) {
  60. Display display = new Display();
  61. try {
  62. walkFonts(display);
  63. } finally {
  64. display.dispose();
  65. }
  66. }
  67.  
  68. }
Add Comment
Please, Sign In to add comment