GraphicsEnvironment.isHeadless()
将true
在以下情况下返回:
- 系统属性
java.awt.headless
已设置为true
- 您在 Unix/Linux 系统上运行,并且没有
DISPLAY
设置环境变量
这是用于检索无头属性的代码:
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;
}
如果您想知道是否有任何可用的屏幕,您可以调用GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()
which 返回所有可用的屏幕。
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;
}
}
}