How to detect if a graphical interface is supported?

前端 未结 5 731
悲哀的现实
悲哀的现实 2021-01-01 12:20

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 should get

相关标签:
5条回答
  • 2021-01-01 12:38

    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().

    0 讨论(0)
  • 2021-01-01 12:41

    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.

    0 讨论(0)
  • 2021-01-01 12:47

    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.

    0 讨论(0)
  • 2021-01-01 12:56

    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 讨论(0)
  • 2021-01-01 12:58

    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.

    0 讨论(0)
提交回复
热议问题