2012-12-18 3 views
0

작업을 수행하고보기에 추가 할 수있는 위젯을 만들 겠지만 완전히 잘못된 각도에서 문제에 접근 할 수 있을지 걱정됩니다. 여기JavaFX의 사용자 정의 Runnable 노드

public void initialize(URL fxmlFileLocation, ResourceBundle resources) 
{ 
    RuntimeWidget runtimeWidget = new RuntimeWidget(); 
    gridPane.add(runtimeWidget, 0, 0); 
} 

@FXML private void handleRunAction(ActionEvent event) throws IOException, InterruptedException 
{ 
    runtimeWidget.start(); 
} 

모든 것이 완벽하게 작동 FXML 컨트롤러에서 위젯을 사용 (프로그램이 실행 된 시간을 추적 위젯)

public class RuntimeWidget extends AbstractWidget 
{ 
    public RuntimeWidget() 
    { 
     this.task = new Task<Void>() 
     { 
      @Override 
      public void run() 
      { 
       final long startTime = System.currentTimeMillis(); 

       while(true) 
       { 
        if (isCancelled()) 
         break; 

        Platform.runLater(new Runnable() 
        { 
         @Override 
         public void run() 
         { 
          long secs = System.currentTimeMillis() -startTime)/1000; 
          String display = String.format("%02d:%02d", (secs % 3600)/60, (secs % 60)); 
          System.out.println(display); 
         } 
        }); 

        try { 
         Thread.sleep(1000); 
        } catch (InterruptedException e) { 
         e.printStackTrace(); 
        } 
       } 
      } 
     }; 
    } 

} 

public abstract class AbstractWidget extends AnchorPane 
{ 
    private Thread thread; 
    protected Task<?> task; 

    public AbstractWidget() 
    { 
    } 

    public void start() 
    { 
     this.thread = new Thread(this.task); 
     this.thread.start(); 
    } 

    public void stop() 
    { 
     this.task.cancel(); 
    } 
} 

구현 내 추상 클래스입니다 좋아,하지만 이건 입니다. 길입니까? 프로그램의 실행 작업을 중지하고 처음부터 다시 시작할 수 있기 때문에 서비스 대신 작업을 사용했지만 일시 중지 및 다시 시작하지 않았습니다.

답변

0

나는 서비스를 사용하기로 결정했습니다. 여러 번 실행할 수있는 기능을 처리하는 것이 훨씬 쉽습니다.

public class MyWidget() extends AbstractWidget 
{ 

    public MyWidget() 
    { 
     this.service. = new MyService(); 
    } 

    private class MyService extends Service<Void> 
    { 
     protected Task<Void> createTask() 
     { 
      @Override 
      return new Task<Void>() 
      { 
       // whatever 
      } 
     } 
    } 
} 
:

public abstract class AbstractWidget extends Whatever 
{ 
    protected Service<?> service; 

    public AbstractWidget() 
    { 
    } 

    public void start() 
    { 
     service.start(); 
    } 

    public void stop() 
    { 
     service.cancel(); 
     service.reset(); 
    } 
} 

은 그럼 당신은 같은 클래스를 만들 수 있습니다