@Test publicvoidwhenHeadlessMode_thenImagesWork(){ boolean result = false; try (InputStream inStream = HeadlessModeUnitTest.class.getResourceAsStream(IN_FILE); FileOutputStream outStream = new FileOutputStream(OUT_FILE)) { BufferedImage inputImage = ImageIO.read(inStream); result = ImageIO.write(inputImage, FORMAT, outStream); } assertThat(result).isTrue(); }
在接下来的这个例子中,我们可以看到所有字体的信息,包括字体的度量,也可以让我们使用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
@Test publicvoidwhenHeadless_thenFontsWork(){ GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); String fonts[] = ge.getAvailableFontFamilyNames(); // assertThat(fonts).isNotEmpty(); Font font = new Font(fonts[0], Font.BOLD, 14); FontMetrics fm = (new Canvas()).getFontMetrics(font); // assertThat(fm.getHeight()).isGreaterThan(0); // assertThat(fm.getAscent()).isGreaterThan(0); // assertThat(fm.getDescent()).isGreaterThan(0); }
HeadlessException
有些设备是需要外部设备支持的,否则会抛出下面的异常:
1 2 3 4
Exception in thread "main" java.awt.HeadlessException at java.awt.GraphicsEnvironment.checkHeadless(GraphicsEnvironment.java:204) at java.awt.Window.<init>(Window.java:536) at java.awt.Frame.<init>(Frame.java:420)
可以使用Frame来进行验证:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
@Test publicvoidwhenHeadlessmode_thenFrameThrowsHeadlessException(){ Frame frame = new Frame(); frame.setVisible(true); frame.setSize(120, 120); }/* 在开关Headless模式后会有不同的结果 开启:通过 关闭 ava.awt.HeadlessExceptionat java.awt.GraphicsEnvironment.checkHeadless(GraphicsEnvironment.java:204) at java.awt.Window.<init>(Window.java:536) at java.awt.Frame.<init>(Frame.java:420) at java.awt.Frame.<init>(Frame.java:385) */