You can use java.awt.GraphicsEnvironment.isHeadless()
to check whether the environment where your program is running supports GUIs or not:
public static void main(String[] args){
if (GraphicsEnvironment.isHeadless()){
// Run console mode
} else {
// Start in GUI mode
}
}
If I were you, though, I'd make this a command-line switch so you can use the console mode in graphic environments, too. For maximum convenience, this would be a non-mandatory option which defaults to some kind of "auto" option, which uses the isHeadless
check, like:
public static void main(String[] args){
final List<String> arguments = Arrays.asList(args);
final int modeIndex = arguments.indexOf("-mode");
final String mode = modeIndex == -1 ? "auto" : argument.get(modeIndex);
if ("auto".equals(mode)) runAuto();
else if ("console".equals(mode)) runConsole();
else if ("gui".equals(mode)) runGui();
else System.err.println("Bad mode: " + mode);
}
private static void runGui(){ ... }
private static void runConsole(){ ... }
private static void runAuto(){
if (GraphicsEnvironment.isHeadless()) runConsole();
else runGui();
}
(TODO: Add error handling, remove magic string literals, etc.)
So, start your program with java YourMainClass
or java YourMainClass -mode auto
and it makes an educated guess whether you want GUI or console, use java YourMainClass -mode console
to force console mode, or java YourMainClass -mode gui
to force GUI mode.