JavaFX和多线程-GIF无法启动

时间:2019-01-06 22:14:19

标签: java multithreading javafx

我尝试实现一个GUI按钮,以便在按下它时执行两个操作-执行主代码(2-3秒)和显示gif-preloader。

我将Task用于此目的,并在setOnAction方法中对其进行初始化和运行。反过来,任务本身使用showGif()方法启动图像。

它们分别正常工作-showGif()打开GIF,任务在控制台中显示与主代码并行工作的计数器。

但是当我将showGif()放入Task时,该方法不起作用。它到达“ pane.setCenter(hb);”行。然后停下来。我以为他没有足够的时间来启动GIF,并在主代码中添加了5秒的延迟-这也没有帮助。

我做错了什么?

除了Task之外,我还尝试了Platform.runLater(new Runnable)-结果是相同的。

按钮动作:

btn_find.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent event) {

            isStarted = true;

            task = new Task<Object>() {
                @Override protected Object call() throws Exception {
                    showGif();
                    return null;
                }
            };

            new Thread(task).start();

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

Gif方法:

protected static void showGif() {
    System.out.println("opening GIF...");

    File file = new File("/Users/user/Desktop/cat-preloader.gif");

    String localUrl = null;
    try {
        localUrl = file.toURI().toURL().toString();

    } catch (Exception e) {
        e.printStackTrace();
    }


    Image image = new Image(localUrl, 200,200, false, true);
    ImageView imageView = new ImageView(image);

    hb = new HBox();

    hb.setStyle("-fx-background-color: lightgrey");
    hb.setOpacity(0.7);
    hb.getChildren().add(imageView);
    HBox.setMargin(imageView, new Insets(300, 100, 60, 200));
    BorderPane.setMargin(hb, new Insets(0, 0,600, 0));

    System.out.println("setting the pane");

    // here thread execution stops
    pane.setCenter(hb); 
    System.out.println("GIF started");
}

0 个答案:

没有答案