How to determine if GraphicsEnvironment exists

徘徊边缘 提交于 2019-11-27 21:30:28

GraphicsEnvironment.isHeadless() will return true in case:

  • the system property java.awt.headless has been set to true
  • your are running on a Unix/Linux system and there is no DISPLAY environment variable set

Here is the code that is used to retrieve the headless property:

    String nm = System.getProperty("java.awt.headless");

    if (nm == null) {
        /* No need to ask for DISPLAY when run in a browser */
        if (System.getProperty("javaplugin.version") != null) {
            headless = defaultHeadless = Boolean.FALSE;
        } else {
            String osName = System.getProperty("os.name");
            headless = defaultHeadless =
                Boolean.valueOf(("Linux".equals(osName) || "SunOS".equals(osName)) &&
                                (System.getenv("DISPLAY") == null));
        }
    } else if (nm.equals("true")) {
        headless = Boolean.TRUE;
    } else {
        headless = Boolean.FALSE;
    }

If you want to know if there is any screen available, you can invoke GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices() which returns all the available screens.

import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;

public class TestHeadless {

    private static boolean isReallyHeadless() {
        if (GraphicsEnvironment.isHeadless()) {
            return true;
        }
        try {
            GraphicsDevice[] screenDevices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
            return screenDevices == null || screenDevices.length == 0;
        } catch (HeadlessException e) {
            e.printStackTrace();
            return true;
        }
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!