I have an application that needs user input for password.
What i want to do is to either read the password from console (if the OS supports one e.g unix) or display a JOptionPane and ask the user to enter his password (if the OS supports graphical interface e.g windows).
Some people may argue that a console will always be available in both the above cases so a console input will be sufficient. But problem is if the Java app starts using javaw.exe then a console is not available. Thus, i need a way to determine if i can do either case.
My problem is how to determine if the environment that the application runs from supports either a console or a graphical interface.
I know that a static method exists
GraphicsEnvironment.isHeadless()
but from the Java doc i think that this method cannot distinguish if the OS supports graphics, but rather than if the OS can support one of the I/O devices (keyboard, mouse, screen).
Does anyone know more about this? Am i able to retrieve if the OS supports console or graphics environment?
Thanks in advance.
GraphicsEnvironment.isHeadless()
will return true
in case:
java.awt.headless
has been set to true
DISPLAY
environment variable setHere 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;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With