开发者

How to detect if a graphical interface is supported?

开发者 https://www.devze.com 2023-01-26 12:55 出处:网络
I need my Java program to have two display modes: a GUI interface and a command line interface.If I run it in Windows, OS X, or another graphical environment I shou开发者_高级运维ld get the GUI interf

I need my Java program to have two display modes: a GUI interface and a command line interface. If I run it in Windows, OS X, or another graphical environment I shou开发者_高级运维ld get the GUI interface, but if I run it via SSH I should get the command line interface.

How can I detect whether a GUI can be displayed or if I should use a command line interface?


You actually have two questions:

1) Check if you run in a headless environment (no graphics). Check this method:

if (GraphicsEnvironment.isHeadless()) {
     // non gui mode
} else {
     // gui mode
}

2) Check which OS you are running under:

System.getProperty("os.name")

However, the second (2) question will return the same name even though you operate in a headless environment.


Both dacwe and vitaut are right. I just wanted to add one recommendation. You should use MVC (model-view-controller) pattern when you are designing your application. So, if it is running in UI mode it uses UIView, otherwise the ConsoleView.

Dacwe recommended you how can you decide automatically which mode to use. Due to Java is cross platform language I think the name is operating system is irrelevant for you. The fact that the system has graphic environment is more relevant, so use GraphicsEnvironment.isHeadless().

System.console() will help you to create shell controlled application.


I recommend adding a command line option that determines whether to use command-line or graphical user interface, because the user may want to use the command-line interface even in the environment where GUI is available.

You can also check if console device is available or not with System.console().


Why not create two classes, one for commandline and one for GUI? Further down you may want to create two products and then you can deliver the headless one without dependencies to graphic libs.


I was looking for te same solution and came up with simply use an argument so when i run my program from comandline the args differs in length

if(args.length > 0) {
    System.out.println("command line mode");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消