2016-05-23 4 views
4

Я пытаюсь создать диалоговое окно ввода javafx, я помещаю его в задачу, но мой код не создает никакого диалогового окна.Создание диалога JavaFX внутри задачи JavaFX

   Task<Void> passwordBox = new Task<Void>() { 
        @Override 
        protected Void call() throws Exception { 
       TextInputDialog dialog = new TextInputDialog("walter"); 
       dialog.setTitle("Text Input Dialog"); 
       dialog.setHeaderText("Look, a Text Input Dialog"); 
       dialog.setContentText("Please enter your name:"); 

       // Traditional way to get the response value. 
       Optional<String> result = dialog.showAndWait(); 
       if (result.isPresent()){ 
        System.out.println("Your name: " + result.get()); 
       } 

       // The Java 8 way to get the response value (with lambda expression). 
       result.ifPresent(name -> System.out.println("Your name: " + name)); 
       return null; 
        } 
       }; 
      Thread pt = new Thread(passwordBox); 
      pt.start(); 

отладки, это происходит внутри следующий метод уловах класса Task

catch (final Throwable th) { 
       // Be sure to set the state after setting the cause of failure 
       // so that developers handling the state change events have a 
       // throwable to inspect when they get the FAILED state. Note 
       // that the other way around is not important -- when a developer 
       // observes the causeOfFailure is set to a non-null value, even 
       // though the state has not yet been updated, he can infer that 
       // it will be FAILED because it can be nothing other than FAILED 
       // in that circumstance. 
       task.runLater(() -> { 
        task._setException(th); 
        task.setState(State.FAILED); 
       }); 
       // Some error occurred during the call (it might be 
       // an exception (either runtime or checked), or it might 
       // be an error. In any case, we capture the throwable, 
       // record it as the causeOfFailure, and then rethrow. However 
       // since the Callable interface requires that we throw an 
       // Exception (not Throwable), we have to wrap the exception 
       // if it is not already one. 
       if (th instanceof Exception) { 
        throw (Exception) th; 
       } else { 
        throw new Exception(th); 
       } 

Если я не прикладывая окно диалога внутри задачи он вызывает к зависанию приложения.

+0

Вы знаете, что 'showAndWait' не блокирует поток приложения JavaFX и, таким образом, не нужно будет работать на другом потоке (на самом деле это не должно ** запускать ** в не-fx-приложении другой поток)? – fabian

+0

Я не уверен, почему вы это делаете. Задача примера, которую вы предоставляете, ничего не делает, кроме как показывать диалог, который может быть выполнен в потоке приложений JavaFX без задачи. Поэтому я не знаю, чего вы пытаетесь достичь, возможно, вы пытаетесь это сделать: [JavaFX2: Могу ли я приостановить фоновое задание/службу?] (Http://stackoverflow.com/questions/14941084/javafx2- can-i-pause-a-background-task-service) – jewelsea

+0

да, мне нужно провести основной поток, чтобы получить вход от пользователя, я попытался использовать концепцию будущей задачи, приведенную в ссылке, но она останавливает приложение и делает отвечать на запросы. – bhavesh

ответ

2

Вы должны убедиться, что диалог открыт на JavaFX Application Thread, так как каждое обновление GUI должно происходить в этом потоке в JavaFX.

Вы можете достичь это нравится:

Task<Void> passwordBox = new Task<Void>() { 
      @Override 
      protected Void call() throws Exception { 
       Platform.runLater(new Runnable() { 

        @Override 
        public void run() { 
         TextInputDialog dialog = new TextInputDialog("walter"); 
         dialog.setTitle("Text Input Dialog"); 
         dialog.setHeaderText("Look, a Text Input Dialog"); 
         dialog.setContentText("Please enter your name:"); 

         // Traditional way to get the response value. 
         Optional<String> result = dialog.showAndWait(); 
         if (result.isPresent()){ 
          System.out.println("Your name: " + result.get()); 
         } 

         // The Java 8 way to get the response value (with lambda expression). 
         result.ifPresent(name -> System.out.println("Your name: " + name)); 

        } 
       }); 

       return null; 
      } 
     }; 
Смежные вопросы