JavaFx in headless mode

后端 未结 5 2044
抹茶落季
抹茶落季 2020-12-10 07:36

Is it possible to run JavaFx in headless mode(in Java 7)? It is being used to generate images on the server but is asking for an X-Server. Does there exist something like ja

5条回答
  •  孤城傲影
    2020-12-10 08:06

    I have an application that can be used interactively (displaying JavaFx dialogs) but also must be able to run non-interactive on a server without display.
    Even though no GUI element is used in non-interactive mode, we got

        Caused by: java.lang.UnsupportedOperationException: Unable to open DISPLAY
        at com.sun.glass.ui.gtk.GtkApplication.(GtkApplication.java:68)
    

    This happens as soon as a class derived from javafx.application.Application is instantiated, which you normally do with your main class.

    Here is the way I solved the problem:

    • I created an additional class GuiAppExecution:

      import java.util.List;
      
      import javafx.application.Application;
      import javafx.stage.Stage;
      
      /**
       * JavaFx launch class for {@link AppExecution}.
       */
      public class GuiAppExecution extends Application {
      
        @Override
        public void start(Stage stage) throws Exception {
          List parameters = getParameters().getRaw();
          AppExecution appExecution = new AppExecution();
          appExecution.launch(parameters);
        }
      
        /**
         * Launches the {@link AppExecution} as JavaFx {@link Application}.
         *
         * @param parameters program parameters
         */
        public void launchGui(String[] parameters) {
          launch(parameters);
        }
      }
      
    • In the main class AppExecution I created a method
      public void launch(List parameters) {
      which parses the parameters and launches the application for both interactive and non-interactive execution.

    • The main method looks like this:

      public static void main(String[] parameters) {
        List parameterList = Arrays.asList(parameters);
        if (parameterList.stream().anyMatch(p -> p.equalsIgnoreCase(BATCH_PARAMETER))) {
          AppExecution appExecution = new AppExecution();
          appExecution.launch(parameterList);
        }
        else {
          GuiAppExecution guiAppExecution = new GuiAppExecution();
          guiAppExecution.launchGui(parameters);
        }
      }
      

      with

      private static final String BATCH_PARAMETER = "-batch";
      

      as the program option that request the non-interactive execution.

    Since GuiAppExecution (which is derived from javafx.application.Application) is not instantiated for non-interactive execution, the JavaFx environment is not started.

提交回复
热议问题