2016-07-22 20 views
0

我試圖以編程方式在JavaFX中調整一組矩形的大小,但是由於線程問題,我遇到了最可能的問題。JavaFX:正在逐步改變後臺線程中的DoubleProperty

即使它是後臺線程中的一個循環,並且應該停止,但程序崩潰時仍會出現widthOfRectangles.set(...。我假設在Platform.runLater中設置DoubleProperty所有我的矩形寬度都將綁定到的位置不起作用。

所以我再次嘗試沒有Platform.runLater(不是下面顯示的代碼),但這一次,它延遲了矩形應該展開/最小化的時間,然後突然跳轉到最終狀態 - 至少它沒有崩潰,但它並不是我尋找的流暢動畫。

是否有可能通過PropertyBindings完全平滑地插入節點的屬性,如果是這樣,我將如何去做而不凍結JavaFX主線程?

expandProgressGraphic = new Thread(new Task<Void>() { 
    @Override 
    public Void call() throws Exception { 
    while (widthOfRectangles.get() < 130) { 
     Platform.runLater(() -> 
     widthOfRectangles.set(widthOfRectangles.get() + (130 - widthOfRectangles.get())/3 + 2)); 

     try { 
     Thread.sleep(30); 
     } catch (InterruptedException e) { 
     e.printStackTrace(); 
     } 
    } 
    widthOfRectangles.set(130); 
    return null; 
    } 
}); 
expandProgressGraphic.setDaemon(true); 

minimizeProgressGraphic = new Thread(new Task<Void>() { 
    @Override 
    public Void call() throws Exception { 
     while (widthOfRectangles.get() > 40) { 
      Platform.runLater(() -> 
       widthOfRectangles.set(widthOfRectangles.get() - (widthOfRectangles.get() - 40)/3 - 2)); 
      try { 
       Thread.sleep(30); 
      } catch (InterruptedException e) {e.printStackTrace();} 
     } 
     widthOfRectangles.set(40); 
     return null; 
    } 
}); 
expandProgressGraphic.setDaemon(true); 


pane.setOnMouseMoved(new EventHandler<MouseEvent>() { 
    @Override 
    public void handle(MouseEvent event) { 
     if(widthOfRectangles.get() != 130 && event.getX() < widthOfRectangles.get() && !expandProgressGraphic.isAlive()) { 
      expandProgressGraphic.run(); 
     } else if(widthOfRectangles.get() != 40 && event.getX() > widthOfRectangles.get() && !minimizeProgressGraphic.isAlive()){ 
      minimizeProgressGraphic.run(); 
     } 
    } 
}); 
+1

你應該調用線程的'start'方法,而不是'run'。 'run'在同一個線程中調用內部'Runnable'。 此外,請考慮使用['Transition'](https://docs.oracle.com/javase/8/javafx/api/javafx/animation/Transition.html) – Itai

回答

0

再次感謝@sillyfly。

我應該使用的Thread.start()代替Thread.run()