2017-08-04 86 views
1

我有一個簡單的javaFx應用程序,它是從html結構中搜索一些文本和一些元素。它有一個小窗口,一個舞臺。程序可以正常運行,但程序運行時,階段(javaFx窗口)不響應,它會凍結。 我以爲我應該在一個新的線程中運行我的舞臺,但它沒有奏效。這是我程序中提到的部分。 如何在沒有窗口凍結的情況下運行我的程序?爲什麼我的舞臺在程序運行時沒有反應? (java fx)

public class Real_estate extends Application implements Runnable { 
    @Override 
    public void start(Stage stage) throws Exception { 
     Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml")); 
     Scene scene = new Scene(root); 
     stage.setScene(scene); 
     stage.show(); 
     stage.getIcons().add(new Image("http://icons.iconarchive.com/icons/paomedia/small-n-flat/1024/house-icon.png")); 
     stage.setTitle("Simple program 0.8"); 
     stage.setWidth(300); 
     stage.setHeight(300); 
     stage.setResizable(false); 

     HtmlSearch htmlSearch = new HtmlSearch(); 
     htmlSearch .toDatabase("http://example.com"); 

    } 

    public static void main(String[] args) { 
     launch(args); 
    } 

    @Override 
    public void run() { 
     throw new UnsupportedOperationException("Not supported yet."); 
    } 

回答

4

運行,需要一個很長時間運行(大概htmlSearch.toDatabase(...))在後臺線程的代碼。你可以這樣做

public class Real_estate extends Application { 

    @Override 
    public void start(Stage stage) throws Exception { 
     Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml")); 
     Scene scene = new Scene(root); 
     stage.setScene(scene); 
     stage.show(); 
     stage.getIcons().add(new Image("http://icons.iconarchive.com/icons/paomedia/small-n-flat/1024/house-icon.png")); 
     stage.setTitle("Simple program 0.8"); 
     stage.setWidth(300); 
     stage.setHeight(300); 
     stage.setResizable(false); 

     HtmlSearch htmlSearch = new HtmlSearch(); 
     new Thread(() -> htmlSearch.toDatabase("http://example.com")).start(); 

    } 

    public static void main(String[] args) { 
     launch(args); 
    } 
} 

這假定htmlSearch.toDatabase(...)不會修改UI;如果是這樣,您需要將修改UI的代碼包裝在Platform.runLater(...)中。參見例如Using threads to make database requests瞭解JavaFX中多線程的更長解釋。

+0

謝謝,它的工作! :) – Kovoliver

相關問題